expect vs pexpect

Yesterday I was trying to automate the setup of ssh keys on my test servers. Of course, the first tool that comes to our mind is the all powerful expect, however, I found some shortcomings trying to do simple things with expect, mainly the lack of a good and comprehensive documentation. So, I’ve struggled with expect looking at examples and after some hours I’ve accomplished my task partially. Looking further, I’ve found pexpect, a simple and clean implementation of expect like functionality in python. As I’m more familiar with python, and since the simple automation stuff is meant to be made easy, I’ve got what I’ve wanted in few lines of code:


import pexpect

def executeCommand(ConnHost, expectString, sendString):
@param ConnHost: ssh spawn pexpect object
@param expectString: What to expect from the server before the command
@param sendString: What to send after expectString was reached
print “Sending command %s” % (sendString)
ConnHost.expect(‘%s’ % (expectString))
ConnHost.sendline(‘%s’ % (sendString))

listHosts = [“host1”, “host2”, “host3”]

remoteUser = ‘user’
remotePass = ‘initial pass in plain text’
publicKey = ‘Put here the public key you have generated with ssh-keygen -d’

for host in listHosts:
print “Initializing connection %s@%s” % (remoteUser,host)
ConnHost = pexpect.spawn(“ssh %s@%s” % (remoteUser,host) )

# Doing the ssh key setup on the given host
executeCommand(ConnHost, ‘.ssword:*’, ‘%s’ % (remotePass))
executeCommand(ConnHost, ‘#:*’, ‘rm -rf .ssh’)
executeCommand(ConnHost, ‘#:*’, ‘mkdir .ssh’)
executeCommand(ConnHost, ‘#:*’, ‘echo %s > .ssh/id_dsa.pub’ % (publicKey))
executeCommand(ConnHost, ‘#:*’, ‘echo %s > .ssh/authorized_keys’ % (publicKey))

That doesn’t mean that I won’t make efforts to learn expect, looks like it’s a great tool with many possibilities, but for simple stuff at least for now I’ll stick with pexpect 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s