使用 expect 脚本 (shell) 捕获错误 return 的通用方法

Generic method to catch error return using expect script (shell)

我有一个 expect 脚本,它在特定的 IP 和端口号上与调制解调器交互。如果生成 telnet 超时或由于某种原因无法连接,我想向用户报告错误。简而言之,我想在命令失败时打印一条错误消息并退出,而不是继续执行脚本。

set -e doesn't work on expect script.

你的建议将帮助我解决这个问题。谢谢。

再次强调我使用的是 expect 脚本,而不是 bash/sh。

#!/usr/bin/expect
try {
    spawn telnet $HOSTIP $HOSTPORT
} on error {
    exit 1
}
....
....

您必须 expect timeouteof 来处理您的情况。

spawn telnet $HOSTIP $HOSTPORT
# To control the timeout value, update this variable
set timeout 60; # 1 min.
expect {
    timeout {puts "Time-out happened;exit 1}
    eof {puts "EOF occured";exit 1} 
    "required-pattern" {puts "The modem is accessible"; exit 0}
}

用您的任何模式替换 "required pattern" 字符串以确认设备的可访问性。