【问题标题】:To exit out of the code if expect condition not met RHEL如果未满足预期条件,则退出代码 RHEL
【发布时间】:2020-03-25 11:50:43
【问题描述】:

我在 Red Hat Linux 8 中使用 expect 编写了一个小代码来检查是否可以使用 ICMP Ping 访问主机。我的意图是如果无法到达目的地,那么执行应该会中断。请在代码下方找到

#!/usr/bin/expect
lassign $argv 1 2
spawn ping -c 2 -i 3 -W 1 $1
 expect  {
    " 0%" {puts "Source is reachable!"}
    " 100%" {puts "Source is not rechable. Please restart IPSEC and check!"}
     eof {break\r }
    }

但是,使用上面的 break 语句,执行将继续到下一行。我是 bash 脚本中 expect 的新手。非常感谢任何帮助

【问题讨论】:

标签: bash shell expect rhel


【解决方案1】:

当然,您不需要对此期望:没有什么需要交互。在普通的 bash 中

result=$( ping -c 2 -i 3 -W 1 "$1 )
if [[ $result == *"100.0% packet loss"* ]]; then
    echo "not reachable"
fi

既然你已经在期待中,你可以使用any Tcl command

set result [exec ping -c 2 -i 3 -W 1 $1]
if {[string first { 100.0%} $result] != -1} {
    puts "Source not reachable"
}

我是 expect 的忠实拥护者,但如果流程不需要交互,还有更简单的方法。


我忘记了 Tcl 对exec 命令的错误处理:如果 exec'ed 命令返回非零,或者如果它向 stderr 发出任何输出,则 exec 将抛出错误。执行ping的方法是:

if {[catch {exec ping -c 2 -i 3 -W 1 $1} result] != 0} {
    puts "ping returned non-zero: $result"
    if {[string first { 100.0%} $result] != -1} {
        puts "Source not reachable"
    }
}

Exhaustively documented on the Tcl wiki

【讨论】:

  • 谢谢,但在我的代码的后面部分,我使用 ssh 连接到这个远程服务器,所以使用了 expect。这就是为什么我需要一个可以在这里与 expect 一起使用的 break 语句
  • 首先,break\r 不是 expect 命令。其次,break 只能在循环中使用:循环在哪里?
  • 嗨格伦,使用上面的 TCL 命令我收到以下错误:2 packets transmitted, 0 received, +2 errors, 100% packet loss, time 2999ms pipe 2 child process exited abnormally while executing "exec ping -c 2 -i 3 -W 1 $1" invoked from within "set result [exec ping -c 2 -i 3 -W 1 $1]" (file "./rtest.exp" line 5)
【解决方案2】:

我在下面添加了代码工作正常:

#!/usr/bin/expect
lassign $argv 1 2
spawn ping -c 2 -i 3 -W 1 $1
expect  {
   " 0%" {puts "Source is rechable!"}
   " 100.0%" {puts "Source is not rechable.Please restart IPSEC and check!";exit 1}
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多