Question:
I use a script to automatically login with Telnet and run some commands on the remote device. But the below code snippet does not work now and then.Here is the said script:
expect -d
to get extra debugging output.Here is the output when
-d
is enabled:Connection closed by foreign host.
Thanks to @glenn jackman,sincerely.
I added
expect_before
to match Connection closed by foreign host.
once expect
is called. But one more problem arises, this script will print out Telnet session closed unexpectedly. Please try again.
even when this script successfully finishes its work and then called send "exit\r"; expect eof
.Is there any way to make the
expect_before
not work anymore when the last expect
command(i.e. expect eof
) is to be invoked?Simply removing the
expect eof
seems a way to achieve this goal. But as far as I can see, it’s not a good solution.Answer:
Notice the “Connection closed by foreign host.”expect
command, expect is looking for two patterns, and the first one found “wins”.- if “connection closed” happens, the messages are printed and the program ends
- if “#” (your prompt) shows up, there’s no specific action, so the
expect
command returns and the rest of your program can carry on
This technique is essential for efficient expect programming where you frequently have to look for multiple patterns.
Looking forward, you might expect to see “Connection closed” at any time: investigate the
expect_before
command.If you have better answer, please add a comment about this, thank you!