1

我在文件中运行 tcl send expect 脚本并作为 ./file 执行

#!/usr/bin/expect
spawn -noecho telnet 42.0.1.11
set timeout 900
expect "login:"
send "admin\r"
expect "Password: "
send "ram\r"
expect "#"
for {set i 0} {$i <= 1000000000} {incr i} {
 some router commands
}

这工作正常,直到路由器重新加载,当路由器重新加载时,此脚本停止,因为 spawn id 未打开。,我想恢复脚本(我不知道重新加载需要多少时间,因为它大部分时间都在变化)。,有吗任何自动恢复脚本的方法

谢谢

4

1 回答 1

0

将您的登录过程包装到一个 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
于 2013-01-21T20:04:38.673 回答