Python modules you should know: pexpect

April 25, 2012 at 07:25 AM | categories: Python, PyMYSK, Howto | View Comments

Next in our series of Python modules you should know is pexpect.

Home page

Use

Pexpect is a pure Python module that makes Python a better tool for controlling and automating other programs. Pexpect is similar to the Don Libes Expect system, but Pexpect as a different interface that is easier to understand.

It runs programs and watches output. When output matches a given pattern Pexpect can respond as if a human were typing responses.

Pexpect can be used for automation, testing, and screen scraping. Pexpect can be used for automating interactive console applications such as ssh, ftp, passwd, telnet, etc.

Unlike other Expect-like modules for Python Pexpect does not require TCL or Expect nor does it require C extensions to be compiled. It should work on any platform that supports the standard Python pty module.

Installation

pip install pexpect

Usage

In the following example i will show you how to automate the creation of a super user in Django. The Django manage.py command is used to create user accounts, it has a no input --noinput option but this option does not allow you to set the password. With this example you are able to create the user account and set the password as if you were typing in the responses.

import pexpect
child = pexpect.spawn('manage.py createsuperuser')
child.expect('Username: ')
child.sendline('username')
child.expect('E-mail address: ')
child.sendline('username@example.com')
child.expect('Password: ')
child.sendline('my weak password')
child.expect('\r\n')
child.expect('Password \(again\): ')
child.sendline('my weak password')

You can use pexpect to do all the things you could do using expect, the source tar ball contains several examples, showing how you can automate the following:

  • Detect if one IP address is taking up an excessive number of connections by running netstat
  • Creates SSH connections to a list of hosts and send commands to all the hosts
  • Start a subshell and log all input and output to a file like the script command
  • Clean up binary files improperly added to CVS
  • Connect to an ftp site and do a few ftp tasks
  • Run a sequence of commands on a remote host using SSH
  • Login to each given server and change the password of the given user
  • Starts an SSH tunnel, monitor the connection and restarts the tunnel if it goes down

And there is more

If you would like to script a process that requires human interaction then pexpect is for you, please refer to the documentation for more information.


blog comments powered by Disqus