Automation With Expect, an Open Source Software Utility
May 24, 2010
I recently came acrossexpect (the expect package in Debian and Ubuntu): 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/*:
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:
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).