expect + how to identify if expect break because time out?

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 10.17.180.23
 [TestLinux]# echo $?
 0

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" }
       }