Automate interactive shell programs with Python pexpect

Some shell programs expect interactive user input. For example if you spawn a root shell with “su” the program asks your for a password. There is no way to pass this password to “su” as a parameter. Another example is to automate an FTP session: start FTP client, provide user and password, do a couple of up- and downloads and exit.

These kind of processes can be automated in Python using the pexpect module. Here is an example on how to run a command as root, interactively sending the password to the waiting process:

import pexpect, sys

# spawn a root shell 
proc = pexpect.spawn("su")
proc.logfile = sys.stdout

# wait until the program finds the string "Password" in the output of the command
# now send the password to the waiting shell

# wait until the command completed (assuming that "#" is part of the next prompt)
# run the whoami command

# wait for next prompt
# ...

This gives the following output:

[email protected]:~$ python script
[sudo] password for myuser: **************

[email protected]:~# whoami