dcsimg

Automation With Expect, an Open Source Software Utility

By Juliet Kemp (Send Email)
Posted May 24, 2010


I recently came acrossexpect (the expect package in Debian and Ubuntu): a powerful utility that can script interactive operations.

Tip of the Trade: The Expect package found in Debian and Ubuntu is a powerful utility that can script interactive operations.

If you're not familiar with TCL syntax, you can get autoexpect from Wi-Fizzle.com. This spawns a shell, and then records everything you do in that shell. Hit Ctrl-C when you're done, and then either run the generated expect script as-is, or edit it to tidy it up a bit. In particular, autoexpect records keystrokes one by one, whereas you can put them all in at once. It records the full prompt, where the $ at the end may suffice.

Here's an example of a script generated with autoexpect then tidied-up. It logs into a server (with single-sign-on in place, so no password needed) and runs rm -rf ~/tmp/*:

set timeout -1
spawn $env(SHELL)
match_max 100000
expect "$"
send -- "ssh serverr"
expect "server*$"
send -- "rm -rf ~/tmp/*r"
expect "server*$"
send -- "logoutr"
expect eof
The expect lines tell the program what to wait for before its next input, and the send lines tell it what to send. Note that you need r at the end of a send line, and can use wildcards.

If you're using expect with ssh, a neater option is the spawn command. This example uses spawn, and makes the script (save as tmpclear and make executable) take a server name as an argument:

#!/usr/bin/expect
if {[llength $argv] != 1} {
puts "usage: tmpclear remotehost"
exit
}
set timeout -1
match_max 100000
spawn ssh $argv
expect "$argv*$"
send -- "rm -rf ~/tmp/*r"
expect "$argv*$"
send -- "logoutr"
expect eof

Expect isn't suitable for all situations, but it can be very handy for cronjobs and other regular tasks. If you need it to send a password, be aware of the security issues -- options include reading it from a private file, or using (restricted) passphraseless SSH keys. Check out the website for more info and examples.

Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of "Linux System Administration Recipes: A Problem-Solution Approach" (Apress, 2009).

Follow ServerWatch on Twitter

Page 1 of 1


Comment and Contribute

Your name/nickname

Your email

(Maximum characters: 1200). You have characters left.