将您的登录过程包装到一个 proc 中,如果您获得 EOF,请再次调用它。这是基本思想,请记住,可能还有其他方法会出错。
编辑:经过一番调查,我已经重写了代码。这已经在 Linux 上通过 Solaris 10 工作站模拟“路由器重新启动”进行了测试(抱歉,没有 Cisco 在此处重新启动)。正如我提到ping
的,实现因操作系统而异,因此proc Ping
可能需要进行更改以适应您的情况。
#!/usr/bin/tclsh
package require Expect
proc RouterLogin {ip user pass} {
spawn -noecho telnet $ip
set timeout 60
expect "login:"
send "$user\r"
expect "Password: "
send "$pass\r"
expect "#"
return $spawn_id
}
proc RouterPing ip {
# ping retry limit - 3
# delay between retries - 30 seconds
set limit 3
set delay 30
set attempt 1
set result false
while {$result == false && $attempt <= $limit} {
set result [Ping $ip]
incr attempt
if {!$result && $attempt <= $limit} {
# wait $delay seconds
after [expr {1000 * $delay}]
}
}
return $result
}
proc Ping ip {
set pingCmd "ping -c 1 $ip"
catch {eval exec $pingCmd} pingRes
if {[regexp "bytes from" $pingRes]} {
return true
} else {
return false
}
}
proc RouterExec {ip user pass commandList} {
set spawn_id [RouterLogin $ip $user $pass]
set timeout 30
foreach cmd $commandList {
send "$cmd\r"
expect {
"#" {
# you are good
puts "Command executed successfully"
}
eof {
# wait 5 minutes
after [expr {1000 * 60 * 5}]
if {[RouterPing $ip]} {
# ping was successful, relogin and resume
set spawn_id [RouterLogin $ip $user $pass]
} else {
# ping was not successful, abort execution
return false
}
}
timeout {
puts "INF: timeout"
return false
}
}
}
send "logout\r"
return true
}
set commandList [list command1 command2 command3]
RouterExec "42.0.1.11" "admin" "ram" $commandList