【问题标题】:Convert output shell to JSON将输出外壳转换为 JSON
【发布时间】: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 @.
  • 顺便说一句,请参阅 DontReadLinesWithForBashFAQ #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


【解决方案1】:

在 bash 中而不是在期望中解决这个问题:

regex=$'CPU utilization for [^\r\n]*'
output=$(/usr/bin/expect -f monitor.exp "$bindip" "$endip" "$name" "$pass" "$company")
if [[ $output =~ $regex ]]; then
  jq -nc --arg cpu_usage "${BASH_REMATCH[0]}" '{"cpu usage": $cpu_usage}'
fi

在 bash 中,[[ $var =~ $regex ]]$var 的内容与$regex 中的正则表达式进行匹配,然后将结果放入一个名为BASH_REMATCH 的数组中。

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2019-02-04
    相关资源
    最近更新 更多