Thursday, November 12, 2009

Automation with expect

For doing project i have to ssh to the Tesla machine in the college as i don't have GPU on my laptop. At times the connection is so slow that its difficult to even type. So i decided to do the coding on my laptop and do the build in the Tesla machine. This needed frequent transfer of files for which i use sftp. Each time invoking sftp and typing in commands is a pain. I wanted to somehow automate this. Googled and came to know about the expect command. The command can be used to automate tasks which needs user interaction. In other words expect talks to other programs using a script. I browsed through the expect man page and I felt writing a script for expect is not that easy for newbies. Well here comes autoexpect script which will generate the script for you.

The expect comes with default installation of most Linux distros but not autoexpect. You can download the required packages from here.

If you are using Ubuntu 9.10 you can use apt

sudo apt-get install expect-dev

The autoexpect script is located in /usr/bin/expect_autoexpect file

Now lets see how we can automate sftp to put a file a.cpp to the some host

girish@MATRIX:~$ expect_autoexpect sftp user@host
autoexpect started, file is script.exp
Connecting to host...

user@host's password:
sftp> mput a.cpp
Uploading a.cpp to /home/user/a.cpp
a.cpp                                              100% 
sftp> bye
autoexpect done, file is script.exp


Now run the script.exp..Bingo!! it  automatically does the sftp operation. with 0% interaction from you.  Ok wait here is a catch.!! Open the script script.exp. You will be shocked to see the password in pure text smiling at you. This is no way acceptable. Well here is the work around.

Add these lines before spawn in the script

send_user "Enter password: "
stty -echo
expect_user -re "(.*)\n" {set PASSWORD $expect_out(1,string)}
send_user "\n"

stty echo

When the script is run it asks for your password and store it in  the variable $PASSWORD. stty -echo ensures password wont be echoed. Change the line where your password is shown to

send "$PASSWORD\r"

You are good to go. But you have to enter password each time you run the script. If you are too lazy for this and not concerned about security, stick on with the original script. Hopefully expect will add an option to encrypt password in the generated script.

No comments:

Post a Comment