GrayFox
GrayFox

Reputation: 185

Bash Expect Telnet: handle premature connection close by server

the question of today is:

If i have an expect script which simply automate some basic telnet operations but sometimes the server "bad act" and close the connections can i handle it and avoid to wait for some timeout occurs?

Some specifications:
The string that i got printed on the console, when the connection is dropped by the server, is the classic "Connection closed by foreign host."

The operations which the expect telnet automation must send are the following:

Authentication phase:

  1. ← Wait for the prompt

  2. → Send the username

  3. ← Wait for the password

  4. → Send the password

  5. ← Wait for the prompt

Command and output phase:

  1. → Send a command string (generally something very simple such a word: "voltage", "temp")

  2. ← Wait the whole output generally wait until the next prompt do the job. (the output contains many symbols and variable values so the wait for prompt seems a good strategy.)

Connection closing phase:

  1. → Send the "exit" command

  2. ← Wait for the legit "Connection closed by foreign host."

NOTE:

The "Connection closed by foreign host." can occur in any moment, eg in any phase. In detail, i'm interested to understand if is possible to fix this when i'm waiting for prompt or output (steps 1,3,5,7) insted of waiting for the connection termination.

Best regards to everyone and thanks to who will try to help!
Stay safe,
Luca

Upvotes: 3

Views: 362

Answers (1)

meuh
meuh

Reputation: 12255

After the spawn you can setup an expect_before command (once) that will be executed every time your script does an expect. Eg

expect_before "Connection closed" { send_user "Unexpected close" ; exit 1 }

See example

Upvotes: 3

Related Questions