Pair-programming with one of my wonderful team colleagues last week, we needed to automate an SSH thing.
SSH doesn't allow the password to be specified on the command line. Usually you'd set up SSH so you don't need to type your passwords). Due to one thing and another, we couldn't do this.
We found Pexpect (a pure Python version of expect). Pexpect makes it easy to automate things that require user interaction (like typing in a password when prompted). As Python was available on the relevant machine, we tried it out - the example using ssh worked first time (here included under the appropriate license):
#!/usr/bin/env python
'''This runs "ls -l" on a remote host using SSH.
At the prompts enter hostname, user, and password.
'''
import pexpect
import getpass
host = raw_input('Hostname: ')
user = raw_input('User: ')
password = getpass.getpass('Password: ')
child = pexpect.spawn("ssh -l %s %s /bin/ls -l"%(user, host))
child.expect('password:')
child.sendline(password)
child.expect(pexpect.EOF)
print child.before
Cool! Another useful addition to the post-modern toolbox.
Posted by ivan at August 7, 2005 4:22 PM