2014-12-02 38 views
1

我正在編寫一個expect腳本來檢查內存使用情況,並且只能在mem使用率小於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 

我需要確保MEM使用小於65%。我如何在預期腳本中做到這一點?

感謝您的幫助。它一直在殺我。

回答

0

您必須在expect本身的幫助下使用正則表達式-re標誌。

可以通過兩種方法來完成此操作。

  1. 匹配所有show performance命令輸出,直到提示,然後應用TCL的遺留的regexp在單獨直接該輸出

  2. 僅匹配所需的值(即MEM使用%值)。

我假設您的設備提示將是#。但是,有些設備的提示可能會有所不同。因此,爲了解決這個問題,我們可以拿出廣義提示圖案,

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%。