Search code examples
linuxshellshsendexcept

Convert output shell to JSON


I have 3 files that are responsible for connecting a firewall and bringing me in response CPU usage, I would like to convert output .exp to JSON, how to do that?

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%'}

Solution

  • Solving this in bash rather than in 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
    

    In bash, [[ $var =~ $regex ]] matches the content of $var against the regex in $regex, and then puts the results in an array called BASH_REMATCH.