Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The target of the following simple expect script is to get the hostname name on the remote machine

Sometimes expect script fail to perform ssh to $IP_ADDRESS ( because remote machine not active , etc )

so in this case the expect script will break after 10 second (timeout 10) , this is OK but......

There are two options

  1. Expect script perform ssh successfully , and performed the command hostname on the remote machine
  2. Expect script break because timeout was 10 seconds

On both cases expect will exit

  • in case of ssh successfully expect will break after 0.5-1 second but in case of bad ssh then it will break after 10 seconds

but I don’t know if expect script perform ssh successfully or not?

is it possible to identify timeout process ? or to verify that expect ended because timeout?

Remark my Linux machine version - red-hat 5.1

Expect script

 [TestLinux]# get_host_name_on_remote_machine=`cat << EOF
  > set timeout 10
  > spawn  ssh   $IP_ADDRESS
  >            expect {
  >                      ")?"   { send "yes\r"  ; exp_continue  }
  >                      word:  {send $PASS\r}
  >                   }
  > expect >  {send "hostname\r"}
  > expect >    {send exit\r}
  > expect eof
  > EOF`

Example in case we not have connection to the remote host

 [TestLinux]# expect -c  "$get_host_name_on_remote_machine"
 spawn ssh
 [TestLinux]# echo $?
share|improve this question
Same question on StackOverflow – glenn jackman Mar 11 '12 at 19:51
up vote 2 down vote accepted

you can expect timeout, some version require -timeout just like -regex to test for the invocation of timeout.

you're expect statement could become

expect {
    ")?"    { send "yes\r"  ; exp_continue  }
    word:   { send $PASS\r}
    timeout { puts "failed to SSH" }
share|improve this answer

I know this isn't exactly what you asked, but I'd like to offer an alternative. Use ssh keys instead of passwords and bash scripting instead of Expect:

output=$(ssh -o ConnectTimeout=10 -o BatchMode=yes -o StrictHostKeyChecking=no $IP_ADDRESS "hostname")

if [ $? -eq 255 ]; then
    # Some error occured while attempting to connect.
    # Success!

This doesn't explicitly tell you there was a timeout vs. failed to log in with a private key, etc., but it beats writing Expect.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.