您必須在expect
本身的幫助下使用正則表達式-re
標誌。
可以通過兩種方法來完成此操作。
匹配所有show performance
命令輸出,直到提示,然後應用TCL的遺留的regexp在單獨直接該輸出
僅匹配所需的值(即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%。