如何期待百分比和空间

时间:2014-12-02 15:28:48

标签: regex expect

我正在制作一个预期脚本来检查内存使用情况,如果内存使用率低于65%,我只能继续执行下一步。

#!/usr/bin/expect -f
spawn telnet $serverip
send "show performance\r"
expect {
    timeout { send_user "\nCPU Usage is too high.\n";exit 1}
    "0-65%" # i need to expect 0-65%
    }

然后继续执行其他命令。

输出是:

CPU used MEM used  RX(Kbps)  TX(Kbps)  RX(Kbps)  TX(Kbps)
1.0%    51.2%      0.000     0.000     1.620     2.426

我需要确保使用的内存少于65%。我怎么能在EXPECT SCRIPT中做到这一点?

感谢您的帮助。它一直在杀我。

1 个答案:

答案 0 :(得分:0)

您必须在expect标志的帮助下在-re内使用正则表达式。

有两种方法可以完成这项工作。

  1. 匹配所有show performance命令输出直到提示,然后在该输出中应用tcl的遗留正则表达式

  2. 仅直接匹配所需的值(即mem使用的%值)。

  3. 我认为您设备的提示符为#。但是,有些设备的提示可能会有所不同。因此,为了处理这个问题,我们可以提出广义的提示模式

    set prompt "#|>|\\\$";
    

    如果您的设备提示不可用,请包含相同的提示。

    #!/usr/bin/expect -f
    
    #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 '$'
    
    spawn telnet $serverip
    
    # Add code for login here
    
    expect -re $prompt;  # Using '-re' flag here to match one one of the prompt.    
    
    # Your some other code here to something if any
    
    # 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 performance\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);
    
    # Applying the tcl's regexp here
    if {[regexp {%\s+([^%]+)} $output ignore mem]} {
        puts "Memory used : $mem"
    }
    

    我将模式用作{%\s+([^%]+)}。在您的输出中,我们有2个百分比符号。第一个对应于使用的CPU,第二个对应于使用的内存。所以,基本上我正在尝试匹配文本% 51.2%

    让我解码模式。

    % - 匹配第一个百分号

    \s+ - 匹配多个空格。

    [^%]+ - 匹配%以外的任何内容(这是我们获取所需值的值,即值51.2)

    那么括号的需要是什么?好吧,那就是分组。 Expect会将匹配的输出保存到expect_out(0,string)。对于nth子匹配,它将保存在expect_out(n, string)上。即,对于第一个子匹配expect_out(1,string)和第二个子匹配expect_out(2,string),依此类推。 Expect会将所有匹配和不匹配的输入存储到名为expect_out(buffer)的变量中。所以,这是短篇小说。还有一件事可能会打扰你。这是什么期望*`在这里做什么?您可以查看here以了解有关相同内容的更多信息。

    这就是第一种方式。现在,我上面描述的第二种方法呢?这有点容易。

    send "show performance\r"; 
    expect {
            -re {%\s+([^%]+)} { set mem $expect_out(1,string); puts "Memory used : $mem" }
            timeout { puts timeout_happened }
    }
    

    这看起来更舒服,无需额外应用单独的regexp。这是它的一个优点。根据您的要求,您可以根据自己的需求使用舒适的任何一种。

    获得该值后,只需将其与if循环进行比较,如果它小于65%。