Using Expect scripts to automate tasks

Slashdot it! Delicious Share on Facebook Tweet! Digg!

Expect Caveats

If your script hangs and doesn't continue, try the command manually yourself and look for the response. If the remote system drops you to a prompt as its final act, then place that in your script (e.g., expect "$ " ).

Be sure you have entered the hard return (\r ) inside the closing quotation mark in your send line. You might also find that your system needs two backslashes on the send line for a hard return (\r ). Sometimes Expect scripts execute too fast, and you won't see your expected response. If that happens, place a sleep command and a number of seconds for the command preceding it to wait for a response, or your data might be ignored.

For example, if you connect to a remote system and there's a delay in creating that connection, your script will continue to execute and fail because it sends commands before the remote system has time to respond.

You have to think about network delays, shell responses, and system timing when scripting in Expect. Like any scripting language, Expect has its quirks, but you'll find that it's an easy way to automate those repetitious keystrokes and procedures. The time you spend debugging your scripts is well worth the effort.

Autoexpect

Of course, some system administrators take lazy to a higher level and even cheat at writing Expect scripts by invoking a shell "watcher" or recorder script named Autoexpect [2].

Once invoked, Autoexpect watches your every keystroke and records it to a file named, script.exp by default. You'll almost certainly have to edit and prune this script to achieve your desired results; however, it can save hours of script debugging to have an almost complete script from which to work. If you simply run a freshly created Autoexpect script, it will likely fail because, if you issued a command that answers your request by displaying information to the screen, the script picks up that answer, too, and copies it into the script file.

For example, if during your Autoexpect session you type ls , the result of that command appears in your script.exp file as well. After you have created a few Expect scripts by hand, you will appreciate the cleanup editing that you have to do in an Autoexpect-created script.

To install Autoexpect, issue a command like:

$ sudo apt-get install expect-dev

You'll likely require many more dependencies for this feature, so prepare yourself for a slight delay while everything installs.

Buy this article as PDF

Express-Checkout as PDF

Pages: 4

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content