2012/06/29

Create a catch-value procedure in Expect 在 Expect 內建立一個取值的函數

This code is a simple example, which catch the value of buffer in procedure, in Expect. User can change certain part in real case.

這程式是一個從暫存記憶體中取值函數的簡單範例,使用者可以依照實際的需要改變部份的內容。


Manual Operation 手動操作


I would like to check the current status, INTEGER: "2", of certain APC port by manually.

我希望能確認某個 APC port 的值(INTEGER: 2)。

jose@QA:~$ snmpget -m none -c private -v 1 172.17.5.177 .1.3.6.1.4.1.318.1.1.4.4.2.1.3.7
MIB search path: /home/jose/.snmp/mibs:/usr/share/mibs/site:/usr/share/snmp/mibs:/usr/share/mibs/iana:/usr/share/mibs/ietf:/usr/share/mibs/netsnmp
Cannot find module (none): At line 0 in (none)
iso.3.6.1.4.1.318.1.1.4.4.2.1.3.7 = INTEGER: 2
jose@QA:~$


Code 程式


The goal of this code is catch the value "2" by procedure in Expect.

這個程式的目標是要在Expect中用函數的方式取出數值「2」。

spawn /bin/bash

send "\n"
expect "jose@" { send "snmpget -m none -c private -v 1 172.17.5.177 .1.3.6.1.4.1.318.1.1.4.4.2.1.3.7\n" }
expect "INTEGER:"
expect "jose@"

proc Catch_value {} {
global expect_out
global value_catch
set value_buffer $expect_out(buffer)
set value_catch [lindex $value_buffer [expr 0]]
}

Catch_value
puts "Catch_value=$value_catch"


If you want to catch certain value, you have
  • expect a value before the value you want,
  • and expect another value after the value you want.
In this case, we want catch the value "2", so we could expect "INTEGER:" and "jose@". Since "2" is between "INTEGER:" and "jose@", thus the value "2" will be stored in buffer. .

如果你想要取得某些值,你必須:
  • expect一個你想取得值前面的值
  • expect 另一個你想取得值後面的值。
在這個案例中,我們想要取得數值「2」,因此我們expect「INTEGER:」和「jose@」,因為數值「2」介於「INTEGER:」和「jose@」中間,這樣數值「2」就會被存進暫存記憶體中。

If you need a procedure to use the global version of expect_out, then a global command must be used in the procedure. And if you want to use the version of value_catch outside of the procedure, then a global command must be used in the procedure too.

在函數內如果你要使用 expect_out 這個 global 變數,那就必須使用 global 命令;如果你想要在函數外也使用 value_catch 這個變數,那也必須使用 global 命令宣告。

FAQ 1 - extra characters after close-brace


If you use a brace behind the close-brace, but no space, Expect will show this error message.

如果你使用一個左大括號緊臨另一個右大括號,而沒有加空白,Expect 就會出現這個錯誤。
proc Catch_value {}{
....
}

沒有留言:

張貼留言