expect script to automate telnet login

2019-01-12 00:44发布

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.

标签: telnet expect
1条回答
家丑人穷心不美
2楼-- · 2019-01-12 01:16

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

查看更多
登录 后发表回答