如何在Expect脚本中处理SSH故障

时间:2014-08-13 04:38:46

标签: loops scripting automation tcl expect

我有一个期望脚本,它登录到设备列表并运行一系列命令。 一切正常,除非其中一个主机无法访问且脚本刚退出。有没有办法让它跳过无法访问的主机&转到剩余的设备?

这是我剧本的主体。

foreach host $hosts {
    spawn -noecho /usr/bin/ssh user@$host
    set timeout 10
    expect {
        "assword:"              { send [string trimright "$pwd" "\r"]   }
        "No route*"             {puts "Host error -> $expect_out(buffer)";exit}
        "Could not resolve*"    {puts "Host error -> $expect_out(buffer)";exit}
    }
    expect "#"
    send "term len 0\r"
    expect "#"
    send "show version\r"
    expect "#"
    send "exit\r"
    expect eof
}

这就是我得到的:

.
. <output of reachable device - R1> 
.
Connection to R1 closed by remote host.
Connection to R1 closed.
ssh: Could not resolve hostname R2: Name or service not known
Host error -> ssh: Could not resolve hostname R1: Name or service not known

1 个答案:

答案 0 :(得分:1)

鉴于Expect本质上是TCL语言的扩展,你的问题实际上归结为“如何在TCL早期结束循环迭代?”。

答案是,使用continue命令而不是exit命令。

相关问题