Question

Here's the code that I have, I explain how I want it to work at the bottom.

set 11 "10.0.0.101"

set 12 "10.0.0.12"


set timeout 20

spawn telnet $11

expect {

"Unable to connect to remote host:" {exit}

"login:"

}

send "root\r"

expect "Password:"

send "root\r"

expect "#"

send "shutdown -r now\r"

expect "#"

send "exit\r"

expect "Connection closed by foreign host."


set timeout 20

spawn telnet $12

expect "login:"

send "root\r"

expect "Password:"

send "root\r"

expect "#"

send "shutdown -r now\r"

expect "#"

send "exit\r"

expect "Connection closed by foreign host."

exit

As you can see, I am using this to reboot devices once a week with a crontab, but if the device is not responding or offline, the script just stops at {exit}
So I want to use like goto command or similar to run the next spawn command in the list. Is there any easy way to do this if there is no goto command ?

Was it helpful?

Solution

Maybe you can include all your command exchange for the first server within the block of code executed after the login prompt is successfully matched?

Something like the following:

set 11 "10.0.0.101"
set 12 "10.0.0.12"

set timeout 20
spawn telnet $11

expect {
    "Unable to connect to remote host:" { }
    "login:" {
        send "root\r"
        expect "Password:"
        send "root\r"
        expect "#"
        send "shutdown -r now\r"
        expect "#"
        send "exit\r"
        expect "Connection closed by foreign host."
     }
}

spawn telnet $12
[...]

If after attempting to connect to $11 you get an "Unable to connect...", it will execute the empty block and move on. If it matches the "login:", it will execute all commands.

You will need to check whether your telnet closes successfully after the "Unable to connect" message (I would think it does), so that you don't end up with multiple spawned sessions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top