Using expect

Let’s give a brief intro to expect. Basically is a tool for automating interactive applications such as FTP, telnet, ssh and similar. Expect has regular expression pattern matching and general program capabilities.

Let’s start installing Expect. Type in your Debian based box:

sudo aptitude install expect

That’s it. You are done.

Now lets write a simple ssh expect script. Substitute user, password and hostname for the user, password and hostname to the machine you want to log into.

#!/usr/bin/expect
spawn ssh user@hostname
expect “user@hostname’s password:”
send “password\r”
expect “$\r”
send “who; pwd; last | head\r”
expect “$\r”
send “date; exit\r”
expect eof

The script is pretty simple. It basically logs into a box and executes date, pwd, who and last commands. But it clearly shows the power of expect for automating tasks.

More info at Wikipedia and Expect homepage.

Leave a Reply