Exception expect脚本中的错误处理

Exception expect脚本中的错误处理,exception,expect,Exception,Expect,我正在复制我的脚本的一个最小的工作示例。它在大多数情况下都可以正常工作,最多可以工作很多天,直到它遇到一个主机,由于某种原因拒绝连接。在这种情况下,脚本停止。我希望脚本忽略任何此类事件并继续到列表中的下一个主机。如何在expect脚本中处理此类错误 #!/usr/bin/expect -f set timeout 5 # The script runs forever. while {1} { # There is a long list of IPs, keeping only tw

我正在复制我的脚本的一个最小的工作示例。它在大多数情况下都可以正常工作,最多可以工作很多天,直到它遇到一个主机,由于某种原因拒绝连接。在这种情况下,脚本停止。我希望脚本忽略任何此类事件并继续到列表中的下一个主机。如何在expect脚本中处理此类错误

#!/usr/bin/expect -f 

set timeout 5

# The script runs forever. 
while {1} {

# There is a long list of IPs, keeping only two for simplicity. 

        set servers [list 172.22.29.254 172.22.2.125 ]
        foreach server $servers {

# Creates a file depending on time and IP.

        set fh [exec date +%Y-%m-%d--%H:%M:%S_$server]

# Telnets a remote host

        spawn telnet $server

        expect Password:
        exp_send "password\r"

# Copies whatever is there. 

        expect ".*"
        expect -re ".*\r"

# Opens the above created file and writes there. 

        set file [open $fh w]
        puts $file  $expect_out(buffer)\n
        close $file

# Connection is now closed. 

        exp_close
        exp_wait
        }
}

问题是你没有做任何错误检查。您以完全线性的方式使用expect命令:等待模式,发送下一条消息。然而,当在任何给定的步骤中都有不止一次的可能模式需要处理时,这种方法就不能很好地工作

幸运的是,expect命令允许您同时指定一组模式,并为每个模式执行操作

例如:

foreach server $servers {
    set fh [clock format [clock seconds] -format "%Y-%m-%d--%H:%M:%S_$server"]
    spawn telnet $server
    expect {
        "word:"              { send "$password\r" }
        "Connection refused" { catch {exp_close}; exp_wait; continue }
        eof                  { exp_wait; continue }
    }
    expect ".*"
    .... rest of script goes here ....
 }
如您所见,当我告诉expect命令查找密码提示并用密码响应它时,我还告诉它,如果我收到一条拒绝连接消息,我将继续生活,如果telnet命令因其他原因而死亡而不是请求密码,继续做生意


这样试试,看看它对你有什么作用。

为什么你的评论前面都有反斜杠?请说明当连接被拒绝时会发生什么。您需要匹配错误消息文本。谢谢Glenn。我错误地注意到,这并没有按原样处理,而是扩大了文章的内容。这就是我所想的,但我想知道是否还有其他方法。编辑问题/答案时,单击橙色?来寻求帮助。也许你可以用Python重写它?Python提供了异常和异常处理,使之更容易实现。