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
proc.expect("[Pp]assword")
# now send the password to the waiting shell
proc.sendline("yourRootPassword")

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

# wait for next prompt
proc.expect("#")
# ...

This gives the following output:

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

[email protected]:~# whoami
whoami
root