发送<command />,期望通过条件测试?

时间:2014-05-23 16:03:09

标签: bash tcl expect

我有一个expect脚本包装在一个bash脚本中,用于执行特定命令,具体取决于是否从Cisco路由器中提取IP地址。我正在尝试编码的算法类似于以下内容:

send -h "ip int br"
expect -re {
    if "192\.[0-9]{1,3}\.{2}[0-9]{1,3}"
    {
        expect 
        {
            "up/up { do these things here }
            "down/down" { do this instead }
        }
    }
    else
    {
        send -h "<another command>"
        expect
        {
            "up/up" { do this }
            "down/down" { or this if down }
        }
    }
}

我该怎么做?我已经尝试使用expect等同于switch语句和-ex标记,如对另一个用户的问题(Making decisions on expect return)的回答中所建议但是没有结果。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我会捕获返回的地址然后对其采取行动。我看到重复的代码,所以尽量减少:

send -h "ip int br"
expect {
    timeout {error "can't find an ip address after 'ip int br' command"}
    -re {\m\d{1,3}(\.\d{1,3}){3}\M}
}
if { ! [regexp {192\.[0-9]{1,3}\.{2}[0-9]{1,3}} $expect_out(0,string)]} {
    send -h "<another command>"
}
expect {
    "up/up" { do these things here }
    "down/down" { do this instead }
}

其他说明:

  • 注意不要把一个块的开口支撑放在它自己的线上,而是用这个命令来拥抱。
  • 将正则表达式放在{braces}中,因为"192\.[0-9]{1,3}\.{2}[0-9]{1,3}"会给你一个类似invalid command name "0-9"的错误 - 括号对于Tcl是特殊的,除非它们在括号内,否则需要进行转义。