当路由器重新加载时,产生路由器会停止,任何方式都会在路由器重新加载后自动重新生成

时间:2013-01-20 12:00:01

标签: tcl telnet expect

我在文件中运行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未打开。我想恢复脚本(我不知道确切需要多长时间重新加载,因为它在大多数时间变化)。 ,有没有办法自动恢复脚本

由于

1 个答案:

答案 0 :(得分:0)

将您的登录程序包裹到一个过程中,如果您获得EOF,请再次调用它。这是基本的想法,只要记住,可能还有其他方法可以解决问题。

编辑:我在调查后重写了代码。这已经在Linux上进行了测试,Solaris 10工作站模拟了“路由器重启”(抱歉没有思科重新启动)。正如我所提到的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