Tuesday, August 07, 2007

Automating tasks with pexpect

I started to use pexpect for some of the automation needs I have, especially for tasks that involve logging into a remote device and running commands there. I found the module extremely easy to use, and the documentation on the module's home page is very good. Basically, if you follow the recipe shown there for logging into an FTP server, you're set.

A couple of caveats I discovered so far:
  • make sure you specify correctly the text you expect back; even an extra space can be costly, and make your script wait forever; you can add '.*' to the beginning or to the end of the text you're expecting to make sure you're catching unexpected characters
  • if you want to print the output from the other side of the connection, use child.before (where child is the process spawned by pexpect)
Here's a complete script for logging into a load balancer and showing information about a load balanced server and its real servers:

#!/usr/bin/env python

import pexpect

def show_virtual(child, virtual):
child.sendline ('show server virtual %s' % virtual)
child.expect('SSH@MyLoadBalancer>')
print child.before

def show_real(child, real):
child.sendline ('show server real %s' % real)
child.expect('SSH@MyLoadBalancer>')
print child.before

virtuals = ['www.mysite.com']
reals = ['web01', 'web02']

child = pexpect.spawn ('ssh myadmin@myloadbalancer')
child.expect ('.* password:')
child.sendline ('mypassword')
child.expect ('SSH@MyLoadBalancer>')

for virtual in virtuals:
show_virtual(child, virtual)

for real in reals:
show_real(child, real)

child.sendline ('exit')

1 comment:

ViNOJ DAViS said...

i used pexpect to get remote machine mac address from the ifconfig command, it was working fine from the terminal i.e the command prompt but when i used that function through cgi it was giving me a Pexpect Exception which is as follows.


(256, \'Traceback (most recent call last):\\n File "/usr/local/https/suid/dossh.py", line 77, in module\\n main()\\n File "/usr/local/https/suid/dossh.py", line 51, in main\\n pssh.login(host,user,passwd)\\n File "/usr/lib/python2.5/site-packages/pxssh.py", line 54, in login\\n spawn.__init__(self, cmd, timeout=login_timeout)\\n File "/usr/lib/python2.5/site-packages/pexpect.py", line 375, in __init__\\n self.__spawn()\\n File "/usr/lib/python2.5/site-packages/pexpect.py", line 446, in __spawn\\n raise ExceptionPexpect(\\\'Error! pty.fork() failed: \\\' + str(e))\\npexpect.ExceptionPexpect: Error! pty.fork() failed: out of pty devices\')')






can u tell me what is the problem.........
do reply to me at this email id if possible......


k_vinoj@yahoo.com

Regards,
--ViNOJ DAViS--

Modifying EC2 security groups via AWS Lambda functions

One task that comes up again and again is adding, removing or updating source CIDR blocks in various security groups in an EC2 infrastructur...