Automate user response using expect / pyexpect scripting tool

A few days ago, I was having problem extracting temperature values from a few of our switches in our HPC cluster.  For some reason, the switches did not  support temperature monitoring through SNMP. They did allow ssh though. So I decided to write a script to automatically send username and password to those switches and execute a particular command to get my task done. Below are those sccripts. One uses expect and the other uses pyexpect :-

You will need to install expect and pyexpect on your system, using yum.
The following script will execute “ls -l” on a remote system.
autologin.sh:-
————-

#!/usr/bin/expect -f
#A simple example is a script that automates an ssh session:
set remote_server “localhost”
set my_user_id “kamran”
set my_password “redhat”
set my_command “ls -l”
spawn ssh $my_user_id@$remote_server $my_command
expect “?assword:*” {send “$my_password\r”}
send “\r”
send “exit\r”
expect eof

 

The following script uses python, and will execute “uptime” on a remote system:-

pyautologin.sh
—————–

#!/usr/bin/python
import pexpect
REMOTE_COMMAND=”uptime”
USER=”fahad”
HOST=”localhost”
PASS=”redhat”
COMMAND=”ssh  %s@%s %s” % (USER, HOST, REMOTE_COMMAND)
child = pexpect.spawn(COMMAND)
child.expect(‘password:’)
child.sendline(PASS)
child.expect(pexpect.EOF)
print child.before

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

I agree to these terms.