期望+如何鉴别期望是否因为超时而破裂?

以下简单期望脚本的目标是获取远程计算机上的主机名称

有时期望脚本不能执行ssh到$ IP_ADDRESS(因为远程机器不活跃等)

所以在这种情况下期望的脚本将在10秒(超时10)之后中断,这可以,但是……

有两个选项

  1. 预期脚本成功执行ssh,并在远程机器上执行命令主机名
  2. 期望脚本中断,因为超时时间是10秒

在这两种情况下,预计将退出

  • 在ssh成功的情况下,预计会在0.5-1秒之后破坏,但如果是不好的ssh,则会在10秒之后破坏

但我不知道是否期望脚本执行ssh成功或不成功?

是否有可能确定超时过程? 或validation期望结束,因为超时?

备注我的Linux机器版本 – 红帽5.1

期待脚本

[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` 

例如我们没有连接到远程主机

  [TestLinux]# expect -c "$get_host_name_on_remote_machine" spawn ssh 10.17.180.23 [TestLinux]# echo $? 0 

你可以期待超时,一些版本需要-timeout就像-regex来testing超时的调用。

你期待的声明可能成为

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

我知道这不完全是你问的,但我想提供一个替代scheme。 使用ssh密钥而不是密码和bash脚本代替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. else # Success! fi 

这并没有明确地告诉你有一个超时与没有用私钥login等,但它击败写预期。