【问题标题】:expect loop / expect_out(buffer) issue期望循环/期望输出(缓冲区)问题
【发布时间】:2014-07-11 17:08:33
【问题描述】:

我是新手。尝试为 cisco 路由器编写一个脚本,该脚本将接口列表作为输入,遍历每个接口,运行命令,保存输出,计算输出中的行数并根据计数执行 if/else 语句。

我在论坛上搜索并根据其他用户的建议拼凑了以下脚本:

现在只是在此处粘贴循环代码:

foreach int $interfaces {

    match_max 20000
    send_user "\n"
    send_user "====== Checking $int ======\n"
    send_user "\n"


    set capture [open output2 w]
    expect "#"
    send "show policy-map $int out\n"
    sleep 1
    expect "#"
    set output $expect_out(buffer)
    puts $capture $output
    close $capture
    set capture 0

    send_user "\n\n---------- $expect_out(buffer) ------------\n\n"
    set count 0
    set count [exec cat output2 | wc -l]
    send_user "\n=========== $int $count ===========\n"

    if {$count<3} {
    puts "Service policy on ! $ip ! $int ! is not working"
    } else {
    puts "Service policy on ! $ip ! $int is working"
    }

    exec echo > output2

}

但是,当我运行脚本时,文件 output2 和 expect_out(buffer) 总是只有一个字符“#”。所以我没有得到所需的结果。出于某种原因,expect_out(buffer) 没有捕获命令“show policy-map $int out”的输出并将其写入文件。我猜这里在循环结构方面存在一个基本的编码错误。

我们将不胜感激!

非常感谢。

【问题讨论】:

    标签: for-loop expect


    【解决方案1】:

    首先,阅读本书以期待学习:Exploring Expect

    从上面的书:

    所有匹配的字符加上之前出现的字符 但不匹配的存储在名为 expect_out(buffer) 的变量中。

    在这种情况下,它只是您所期望的模式,它是#。所以你看对了。

    现在,对于您的要求,请参考How to access the result of a remote command in Expect。此链接为您提供了必要的解释。

    【讨论】:

    • 感谢您的回复。你是对的,我正在匹配“#”,但我也希望在“#”之前看到命令的结果在 expect_out(buffer) 中。但它只显示匹配的模式。
    • 再次感谢您的支持。我发现了这个问题。在我感兴趣的那个之前有一个“#”。更改了模式匹配,现在它可以工作了。
    【解决方案2】:

    再次感谢您的支持。我发现了这个问题。在我感兴趣的那个之前有一个“#”。更改了模式匹配,现在它可以工作了。

    【讨论】: