Reputation:
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
On both cases expect will exit
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
Upvotes: 4
Views: 20102
Reputation: 137567
To do sensible things on timeout, you need to tell expect what should happen:
set timeout 10
expect {
")?" { send "yes\r" ; exp_continue }
"word:" { send "$PASS\r" }
timeout { puts "timed out during login"; exit 1 }
}
set timeout -1 ; # Infinite...
expect ">" { send "hostname\r" }
expect ">" { send "exit\r" }
expect eof
exit
Notice above how I use exit 1
when I hit an error. Your shell will be able to pick that up through $?
, etc. (Without the 1
argument, the exit
command will cause the script to terminate “successfully”; the same happens if you drop off the bottom of the script.)
Upvotes: 18
Reputation: 55443
Not really answering the original question, but why are you talking to SSH interactively when you just can pass it a script to execute? It's a shell after all.
I mean, just run:
ssh user@host '/usr/bin/hostname'
and ssh will spawn the hostname
command remotely and connect its stdout to the stdout of the process which spawned ssh
.
Back to the point—this looks like an example on how to bind an action to a timeout condition.
Upvotes: 4