期望脚本中的错误处理

时间:2014-08-12 09:50:18

标签: 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 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
        }
}

1 个答案:

答案 0 :(得分:0)

问题是你没有做任何错误检查。您以完全线性的方式使用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命令因某些其他原因而死,而不是要求输入密码,那么继续开展业务。

以这种方式试试,看看它是如何运作的。

相关问题