【发布时间】:2020-07-06 03:35:58
【问题描述】:
我有 3 个文件负责连接防火墙并让我响应 CPU 使用率,我想将输出 .exp 转换为 JSON,该怎么做?
monitor.exp:
# It has more data above, I posted only the part that matters
expect "#"
send "\ r"
expect "#"
send "show cpu usage \ r"
expect "#"
send "exit \ r"}
}
monitor.conf:
10.0.0.0:10.0.0.1:local-dns:admin@admin#:Brazil
monitor.sh:
for i in `cat /tmp/monitoring/monitor.conf | grep -v ^#`
do
bindip=`echo $i|cut -d: -f1`
endip=`echo $i|cut -d: -f2`
name=`echo $i|cut -d: -f3`
pass=`echo $i|cut -d: -f4`
company=`echo $i|cut -d: -f5`
/usr/bin/expect -f /tmp/monitoring/monitor.exp $bindip $endip $name $pass $company
done
输出显示:
firewall-customer/pri/act#
firewall-custome/pri/act# show cpu usage
CPU utilization for 5 seconds = 90%; 1 minute: 85%; 5 minutes: 80%
期望:
{'cpu usage': 'CPU utilization for 5 seconds = 90%; 1 minute: 85%; 5 minutes: 80%'}
【问题讨论】:
-
您需要指定 JSON 输出的外观。它可以像
"CPU utilization for 5 seconds = 90%; 1 minute: 85%; 5 minutes: 80%"一样简单——这是有效的 JSON。不过,我怀疑您正在寻找比这更复杂的 JSON 结构。 -
...就您的问题是“我如何将使用期望检索到的数据编码为 JSON?”,wiki.tcl-lang.org/page/JSON 的所有资源都适用于
expect(本身就是 TCL 扩展)。请特别注意其中包含指向jq的链接,我们有许多现有的问答条目告诉您如何使用。 -
@LuisHenrique,
{'cpu usage': 'CPU utilization for 5 seconds = 90%; 1 minute: 85%; 5 minutes: 80%'}不是有效的 JSON。 JSON 只允许双引号而不是单引号具有语法意义。如果您真正想要的是 Python 数据(确实 允许在该上下文中使用单引号),请考虑使用原生 Python 库pexpect而不是基于 TCL 的 @987654334 @. -
顺便说一句,请参阅 DontReadLinesWithFor 和 BashFAQ #1。摆脱所有
echo | cut并执行while IFS=: read -r bindip endip name pass company; do [[ $bindip = #* ]] && continue; ...; done </tmp/monitoring/monitor.conf效率更高
标签: linux shell sh send except