Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for prompt in expect script

I need an expect script to wait for an issued command to finish, and then log out from telnet. Here is the script:

spawn telnet host
send "username\r"
send "password\r"
sleep 3
send "custom_command\r"
while {???}
{
    sleep 1
}
send "logout\r"
expect eof

The part that I don't know how to phrase is ???. I basically just need to wait for the prompt to show up, and as soon as it shows up, the script should end. I'm guessing it should be something like [gets line != "prompt>" ].

like image 666
Ulrik Avatar asked Dec 07 '22 00:12

Ulrik


2 Answers

I tried the expect command, but it didn't work, after some research, trial and error I figured out the following:

  1. Use expect "prompt>\r" instead of expect "prompt>"
  2. Curly braces need to be on the same line as expect command, like this expect "prompt>\r" {
  3. Use set timeout -1 to wait for the prompt infinitely, instead of 10 seconds

So, the answer is:

spawn telnet host
send "username\r"
send "password\r"
sleep 3
set timeout -1
send "custom_command\r"
expect "prompt>\r" {
    send "logout\r"
    expect eof
}
like image 111
Ulrik Avatar answered Jan 14 '23 14:01

Ulrik


You should really expect something before you send something, to get the timing right. Something like:

exp_internal 1      ;# expect internal debugging. remove when not needed
spawn telnet host
expect "login: "
send "username\r"
expect "Password: "
send "password\r"
set prompt {\$ $}   ;# this is a regular expression to match the *end* of
                     # your shell prompt. Adjust as required.
expect -re $prompt
send "custom_command\r"
expect -re $prompt
send "logout\r"
expect eof
like image 39
glenn jackman Avatar answered Jan 14 '23 13:01

glenn jackman