Saturday, January 4, 2014

using expect tool in shell script

Often times we run into problems with servers and there is a need to access multiple of them (if working in a cluster environment). Mostly, SSH is used to login into these systems and run the appropriate commands for debugging or maintenance purposes. However, SSH provides PKI-based or password-based authentication. with Password-based setup, it is very annoying to provide your password each time. Same situation occurs with other services such as FTP, telnet, rlogin, passwd etc. which needs user interaction for providing password to these commands. This makes it hard to write a automated script that requires no such user-interaction and speed-up the process. For this purpose, expect tool (http://expect.sourceforge.net/) is quite handy. For SSH only, I have tried sshpass tool and it also works with SSH. The following section provides details about using the expect tool.

Use expect on Ubuntu or other linux distros

In order to user it, first check if you have expect command available. in case you don’t have it, first install it on ubuntu using sudo apt-get install expect. For other linux distro, use appropriate package manager such as yum to install it.

Once it is installed, use the following script.

#!/usr/bin/expect

spawn ssh khawar@IP_ADDRESS/HOSTNAME
expect "*?assword:*"
send - "<PASSWORD>"
send — “\r"
send -- "\r"
send -- "ls\r"
expect eof


replace <password> with your remote machine password and this will let you login into the remote machine. This example will allow you to login into the given host and see its entires because we are sending ‘ls’ command.

you can use scp command here for file transfer. the script will be straight forward.

#!/usr/bin/expect

spawn scp /home/khawar/boto_s3_test.py khawar@IP_ADDRESS:~/
expect "*?assword:*"
send - "<PASSWORD>"
send — “\r" expect eof

for sftp use the following script.

#!/usr/bin/expect

spawn -nottycopy -nottyinit sftp khawar@IP_ADDRESS
expect "*?assword:*"
send - "<PASSWORD>"
send — “\r" expect “sftp>" send -- "put \r" expect "sftp>" send -- "quit\r" expect eof

No comments: