期望脚本输出

时间:2018-07-26 20:25:02

标签: linux bash shell scripting expect

我正在尝试使用Expect脚本从固件输出ARP表的大小,以便对其进行图形化处理。在执行以下代码后,将显示输出到屏幕:

/usr/bin/expect -f -<< EOD
spawn ssh test@1.2.3.4
sleep 1
expect {
"*word:" {send "password\r"}
}
sleep 1
expect {
"*>" {send "show arp all | match \"total ARP entries in table\"\r"}
}
sleep 1
expect {
"*>" {send "exit\r"} 
}
expect eof
EOD

spawn ssh test@1.2.3.4
FW-Active
Password:
Number of failed attempts since last successful login: 0
test@FW-Active(active)> show arp all | match "total ARP entries in table"
total ARP entries in table :        2861

我想做的是只能输出表中ARP总条目中指示的数值。我假设我需要一些如何“剪切”或“ awk”或仅提取数字的方法,但是我没有任何运气。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您将整个命令的输出存储在一个变量中,例如a。 这样的事情可能会起作用。由于您使用的是Expect,因此您可能需要弄清楚如何将输出存储为变量,从而可以对其进行操作。在示例中,我将输出存储为$ a。

$ echo $a
total ARP entries in table : 2861
$ echo ${a% *}
total ARP entries in table :
$ echo ${a% *}-
total ARP entries in table : -
$ echo ${a##* }
2861

逻辑说明(BASH中的参数/变量替换)
1)要去除/剥离左侧部分,请使用#来获取第一个匹配字符值(从左侧读取/解析),使用##来获取最后的匹配字符/值。通过在*<value> {中使用}来起作用。

2)要除去/剥离右侧部分,请使用%来获得第一个匹配字符值(从右侧读取/解析),使用%%来获得最后一个匹配字符/值。通过在<value>* {中使用}来起作用。

或者,如果您不想存储输出或任何东西,只需执行以下操作:

show arp all | match "total ARP entries in table" | grep -o "[0-9][0-9]*"

或者(以下假设您没有更改

show arp all | match "total ARP entries in table" | sed "s/  *//g"|cut -d':' -f2
相关问题