期待+如何识别是否因为超时而打破?

4 linux shell ksh tcl expect

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

有时候期望脚本无法执行ssh到$ IP_ADDRESS(因为远程机器不活动等)

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

有两种选择

  1. Expect脚本成功执行ssh,并在远程计算机上执行命令hostname
  2. 期待脚本中断,因为超时为10秒

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

  • 如果ssh成功预期会在0.5-1秒之后中断,但是如果ssh不好则会在10秒后中断

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

是否可以识别超时过程?或者验证期望因超时而结束?

备注我的Linux机器版本 - red-hat 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`
Run Code Online (Sandbox Code Playgroud)

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

 [TestLinux]# expect -c  "$get_host_name_on_remote_machine"
 spawn ssh 10.17.180.23
 [TestLinux]# echo $?
 0
Run Code Online (Sandbox Code Playgroud)

Don*_*ows 15

要在超时时做出明智的事情,你需要告诉预期会发生什么:

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
Run Code Online (Sandbox Code Playgroud)

请注意上面exit 1我遇到错误时的使用方法.你的shell将能够通过$?等方式选择它.(没有1参数,该exit命令将导致脚本"成功"终止;如果你从脚本的底部删除,也会发生同样的情况.)