Using expect and autoexpect to automate tasks in Linux

No Comments

As administrators of hundreds of Linux servers, we are always looking to automate tasks at RackWire. One tool we have come to really appreciate is Expect. Expect is a program that “talks” to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. This is great for automating tasks over telnet, ftp, sftp, ssh and others.

Here is an example of a simple Expect script that logs into a remote machine and downloads a file over SFTP:


spawn sftp user@myserver.com
expect -exact "Connecting to myserver.com...\r
user@myserver.com's password: "
send -- "MySecretPassword\r"
expect -exact "\r
sftp> "
send -- "progress\r"
expect -exact "progress\r
Progress meter disabled\r
sftp> "
send -- "get index.html\r"
expect -exact "get index.html\r
Fetching /home/user/index.html to index.html\r
sftp> "
send -- "exit\r"
expect eof

In the above example, our expect script connects to myserver.com over SFTP, logs in, disables the progress meter (a good practice in case the file size is a variable), downloads index.html and then logs out. This could be a useful script if you needed to download a specific file every hour. If the job we were automating was more complicated than the above example, it may take a while to write the expect script. Enter autoexpect.

Autoexpect is used to generate an Expect script from watching a session. Basically you tell autoexpect what program you want to run and what file you want to save the results to. You then interactively walk through the program and it will generate your expect script for you. For example, If I wanted to automate the creation of my example expect script above, I would simply do this:

autoexpect -f sftp-example.exp sftp user@myserver.com

I would then walk through the sftp prompts as I would a normal session. When completed, we will have a new file created named “sftp-example.exp” which contains our expect script. To run it, we would do:

expect sftp-example.exp

There you have it, your SFTP session is now fully automated!

Share the Rack:
  • Twitter
  • Facebook
  • Digg
  • LinkedIn
  • del.icio.us
  • StumbleUpon
  • Google Bookmarks
  • Print
 
Tags: , ,
Posted in: Linux Virtuozzo VPS, RackWire News, Virtual Servers (VPS)

Leave a Reply

You must be logged in to post a comment.