【问题标题】:Set output from expect "send" command as a TcL Variable将期望“发送”命令的输出设置为 TcL 变量
【发布时间】:2014-11-10 02:58:58
【问题描述】:

我已经搜索过这个,但没有找到真正适合我的答案。

我想将通过 expect 发送的命令的输出设置为变量,我将使用 TcL 对其进行解析。这将主要用于未安装 TcL 的设备。防火墙、路由器和交换机等。

类似这样的:

send "show interface status"

#output of show command on device  
Port      Name               Status       Vlan       Duplex  Speed Type
Gi1/1     trunk to switch    notconnect   100          auto   auto 10/100/1000-TX
Gi1/2     this is a test por notconnect   100          auto   auto 10/100/1000-TX
Gi1/3                        notconnect   routed       auto   auto 10/100/1000-TX
Gi1/4                        notconnect   400          auto   auto 10/100/1000-TX

我想让变量成为一个列表,如果它有 TcL,我通常会在设备上使用它:

set showInterface [split [exec "show interface status"] \n]

【问题讨论】:

    标签: tcl expect


    【解决方案1】:

    使用send 命令后,您需要使用expect 命令来获取所有显示命令的输出类似,

    #This is a common approach for few known prompts
    #If your device's prompt is missing here, then you can add the same.
    set prompt "#|>|:|\\\$"; # We escaped the `$` symbol with backslash to match literal '$'
    
    #Your code to telnet to the device here...
    
    # This is to clean up the previous expect_out(buffer) content
    # So that, we can get the exact output what we need.
    expect *; 
    
    send "show interface status\r"; # '\r' used here to type 'return' .i.e new line
    expect -re $prompt; # Matching the prompt with regexp
    
    #Now, the content of 'expect_out(buffer)' has what we need
    set output $expect_out(buffer);
    
    set interfaces [ split $output \n ]; # Getting each interfaces info in a list.
    

    您可以查看here 以了解更多关于您需要expect * 的原因。

    更新:

    默认情况下,expect 的缓冲区大小限制足以保证模式最多可以匹配输出的最后 2000 个字节。这只是 25 行 80 列屏幕上可以容纳的字符数。 (即25*80=2000)

    expect 保证可以进行的最大匹配大小由match_max 命令控制。例如,以下命令可确保 expect 可以匹配最多 10000 个字符的程序输出。

    match_max 10000 
    

    match_max 的数字不是可以匹配的最大字符数。相反,它是可以匹配的最大字符数中的最小值。或者换一种说法,可以匹配比当前值更多的值,但不能保证更大的匹配。没有参数,match_max 返回当前生成的进程的值。

    %
    % package require Expect
    5.43.2
    % match_max
    2000
    % match_max 10000
    % match_max
    10000
    %
    

    将缓冲区大小设置得足够大会减慢您的脚本速度,但前提是您让输入不匹配。当字符到达时,模式匹配器必须在连续越来越长的输入量上重试模式。因此,最好将缓冲区大小保持在您实际需要的范围内。

    【讨论】:

    • 这很好用,但似乎 $expect_out(buffer) 不足以容纳输出。缓冲区大小是否可调?比如,如果你想“cat”一个文件,然后用 TcL 解析输出?
    猜你喜欢
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2022-01-24
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多