16

How do I add timeout for "expect" in the following script? I want to set it as 120 seconds.

#!/bin/bash
HOST="localhost"
USER="myuname"
PASS="mypassword"

VAR=$(expect -c "
spawn ssh $USER@$HOST
expect \"password:\"
send \"$PASS\r\"
expect \"\\\\$\"
send \"ls\r\"
expect -re \"$USER.*\"
send \"logout\"
")

echo "==============="
echo "$VAR"

3 Answers 3

15

The default timeout for expect is 10 seconds according to its manpage. To change it to 120 seconds, before spawn ssh $USER@$HOST, add the line

set timeout 120

to make this

VAR=$(expect -c "
set timeout 120
spawn ssh $USER@$HOST
expect \"password:\"
send \"$PASS\r\"
expect \"\\\\$\"
send \"ls\r\"
expect -re \"$USER.*\"
send \"logout\"
")
0
5

According to the following extract of the man page for expect:

" expect [[-opts] pat1 body1] ... [-opts] patn [bodyn]

waits until one of the patterns matches the output of a spawned process, a specified time period has passed, or an end-of-file is seen. If the final body is empty, it may be omitted.

Patterns from the most recent expect_before command are implicitly used before any other patterns. Patterns from the most recent expect_after command are implicitly used after any other patterns.

If the arguments to the entire expect statement require more than one line, all the arguments may be "braced" into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces.

If a pattern is the keyword eof, the corresponding body is executed upon end-of-file. If a pattern is the keyword timeout, the corresponding body is executed upon timeout. If no timeout keyword is used, an implicit null action is executed upon timeout. The default timeout period is 10 seconds but may be set, for example to 30, by the command "set timeout 30". An infinite timeout may be designated by the value -1. If a pattern is the keyword default, the corresponding body is executed upon either timeout or end-of-file.

If a pattern matches, then the corresponding body is executed. expect returns the result of the body (or the empty string if no pattern matched). In the event that multiple patterns match, the one appearing first is used to select a body. ... "

1

@DerfK has answered your question. I'd refactor your script for maintenance though:

#!/bin/bash
export HOST="localhost"
export USER="myuname"
export PASS="mypassword"

script=<<'END_OF_SCRIPT'
    set timeout 120
    spawn ssh $env(USER)@$env(HOST)
    expect "password:"
    send "$env(PASS)\r"
    expect "\$"
    send "ls\r"
    expect -re "$env(USER).*"
    send "logout"
    expect eof
END_OF_SCRIPT

VAR=$(expect -c "$script")

echo "==============="
echo "$VAR"
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .