Automating processes through Expect
Archive - Originally posted on "The Horse's Mouth" - 2008-04-05 08:03:46 - Graham EllisWhat is Expect? Let me give you an example of how it's used to help answer that question.
I want to connect to a remote host that I can access through FTP, and have a look at all the files with "top", "sql" and "txt" in their names in my home directory. And that's something I need to do on a regular basis - perhaps checking logs on a web server.
I could type in the instructions longhand - but that would get monotonous on a regular basis - so I would prefer to run FTP controlling it like a puppet on a string - and that string in Expect.
Firstly, I do the job manually, once, and note down the exact prompts that I get, and the exact strings I type in. You noted, I hope, that I say "exact", didn't you - I must get spaces, carriage returns, line feeds right.
Then I write my code. The spawn command is used to trigger FTP. The expect command is used to await a prompt. And the send command is used to answer those prompts. Finally, I can use the variable called expect_out(buffer) which stores the complete response received prior to each "expect" to look at my results.
Here's a working example.
log_user 0
# Expect is a Tcl extension
# So all the Tcl commands are available too
puts "yes I am tickling"
spawn ftp 192.168.200.67
expect "): "
send "trainee\r"
expect "sword: "
send "abc123\r"
expect "ftp> "
send "ls\r"
expect "ftp> "
# The response we just got will have included
# the lines we want (and much more!) so that we
# can now use regular Tcl commands to extract it
set parts [split $expect_out(buffer) \n]
foreach line $parts {
if {[regexp top|sql|txt $line]} {puts $line}
}
# Close out cleanly
send "quit\r"
expect "eof"
That's very much a "spike" solution - a demonstration of principles; the expect command can wait for a whole series of alternatives (including error conditions) and the application above could be extended to handle them as appropriate, for example. And you can even run multiple spawned processes in parallel.

Expect, and Tcl are covered on our Tcl and Expect course. We cover Tk on our Tk course