将输出 shell 转换为 JSON

Convert output shell to JSON

我有 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

The output show:

firewall-customer/pri/act#
firewall-custome/pri/act# show cpu usage
CPU utilization for 5 seconds = 90%; 1 minute: 85%; 5 minutes: 80%

Desired:

{'cpu usage': 'CPU utilization for 5 seconds = 90%; 1 minute: 85%; 5 minutes: 80%'}

在 bash 中解决这个问题,而不是在 expect 中:

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的数组中.