expect script to automate telnet login

woodstok picture woodstok · Oct 17, 2011 · Viewed 45.8k times · Source

I have been trying to create an expect script to automatically login to my device through telnet

If there are no multiple possibilities for the expect command , the script works fine, logs in to the device.

#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set port [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]

spawn telnet $ip $port
expect "'^]'." sleep .1;
send "\r";
sleep .1;
expect   "login:"
send "$user\r"
expect "Password:"
send "$password\r";
interact

The script above works fine and logs in successfully when i pass the correct parameters. But once i add additional branches(for error handling) to the expect command , the script gets stuck at login: prompt.After some time it prints Script Error Any help?? Erroneous script below.

#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set port [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]

spawn telnet $ip $port
expect "'^]'."
sleep .1;
send "\r";
expect
{
  "login:"
  {
        send "$user\r"
        expect "Password:"
        send "$password\r";
        interact

  }

  "host: Connection refused"
  {
    send_user "ERROR:EXITING!"
    exit
  }

}

PS: This script is to be further developed to wait for additional prompts to load different build images on the device. Only telnet(console) connection works. so ssh is not an option.

Answer

woodstok picture woodstok · Oct 17, 2011

My bad. The problem was with the curly braces. They are supposed to be at the same line as the expect command .