Monday, July 10, 2006

Expect Scripting

I attempted expect scripting for the first time today. I must say, if I used it more, I'd be writing a complete tutorial to it. I had trouble finding a good, verbose, tutorial on it. As it is, I'll just post a (working) version of my scp script that uses expect to automate the process:


#!/usr/bin/expect --
set localfile [lindex $argv 0]
set timeout 30
spawn /usr/bin/scp $localfile user@host:~remotedir

expect {
"password:" {
send "mypass\r"
interact
} "yes/no)?" {
send "yes\r"
set timeout -1
} timeout {
exit
} eof {
exit
}
}


What this does, is take an argument off the command line as the local file, and copies it to the remote server as hard coded in the file. I wanted to keep it simple, but the two things I wanted to point other that I had (a little) trouble finding are:

1. To access command line variables, it's kind of funky. So you will want to declare normal local variables at initialization like:
set localfile [lindex $argv 0]
With $argv 0 being the first argument. I couldn't get this to work with the C-style $argv[0] - it causes a syntax error.

2. When you are spawning a command that actually does something and prints information to the screen, you need to tell expect to interact. Otherwise, it will just quit after performing the operations you tell it to explicitly.