'connecting to switch via ssh using expect

I'm trying to run an script to connect to a Procurve 4204vl switch using expect. This is the code I created:

#!/usr/bin/expect -f
set timeout 20
spawn ssh -l user 192.168.0.10 
expect "[email protected]'s password:"
send "1234"
send "\r"
expect "Press any key to continue" 
send "j\r"
send "conf"
send "\r"
send "no ip route 89.19.238.2 255.255.255.255 192.168.0.12"
send "\r"
send "exit"
send "\r"
send "exit"
send "\r"
send "exit"
send "\r"
expect "Do you want to log out [y/n]?"
send "y"

I run this using simply expect script.exp, and the problem is I got these errors:

  1. the route is not deleted
  2. I got the following error on screen after the script execution is finished:

    Press any key to continue invalid command name "y/n" while executing "y/n" invoked from within "expect "Do you want to log out [y/n]?"" (file "script.exp" line 19)

So, how could I solve this problem? Thank you.

PS: if I comment all the "exit" lines and also the log out question, then add a last line with the "interact" command, the script works fine.



Solution 1:[1]

For route not deleted, what output is the program giving you? Do you see any errors from the router?

In expect and Tcl the square brackets are the syntax to execute a command, quite like backticks in the shell. The simplest solution is to use braces instead of double quotes to prevent command interpolation:

expect {Do you want to log out [y/n]?}

Braces act like single quotes in the shell.

Solution 2:[2]

send "logout\r"
expect {
    "Do you want to log out" {
        send "yy"
        exp_continue
    } "Do you want to save current configuration" {
        set result $expect_out(0,string);
        puts "save..."
        send "y"
        puts "ok"
    } eof {
        puts "end of script"
    }
}

Solution 3:[3]

What it worked for me is to use regex (-re argument) and avoid using the characters [] in the expression:

expect -re "Do you want to log out"

It's also useful because if the output from the command is too long or dynamic, using static expression is limited.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 glenn jackman
Solution 2 piaf
Solution 3