Wednesday 13 April 2022

SNMP to XML

(very old draft - may not be complete) I wanted to be able to query SNMP data from a device and turn it into XML so that it can be queried with XPath or XQuery. The idea is to be able to script something like this:
snmpget -v2c -c$community -OXf $host $oid | ./pc-snmp2xml.sh
eg.
snmpget -v2c -cpublic -OXf 10.0.0.1 ifInOctets.1 | ./pc-snmp2xml.sh
So,
snmpget -v2c -cpublic -OXf 10.0.0.1 ifInOctets.1
might return
.iso.org.dod.internet.mgmt.mib-2.interfaces.ifTable.ifEntry.ifInOctets[1] = Counter32: 2606713050
whereas this
snmpget -v2c -cpublic -OXf 10.0.0.1 ifInOctets.1 | ./pc-snmp2xml.sh
returns
snmpbulkwalk works just as well to convert the whole MIB to XML. I have tested this script with Apple Time-Capsule, Nortel 425 switch, MacBook Pro, and a Billion 7404 ADSL router. I had to pre-process the MacBook Pro and Billion router output to remove newline characters and duplicate output respectively. I wrote the SNMP to XML script in AWK because I thought AWK's pattern matching and parsing would simplify the task. I'm not convinced, but it was a good learning exercise. This is the clean-up script.
#!awk # This converts snmp output like this: # .iso.org.dod.internet.mgmt.mib-2.host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunName[4592] = Hex-STRING: 6A 61 76 61 00 00 00 00 00 00 00 00 00 00 00 00 # 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 # 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 # into this: # .iso.org.dod.internet.mgmt.mib-2.host.hrSWRun.hrSWRunTable.hrSWRunEntry.hrSWRunName[4592] = Hex-STRING: 6A 61 76 61 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0 0 00 00 00 00 00 00 # where multiple lines of data are converted into a single line by eliminating the new-line characters # process expected OID lines that start with . /^(\.).*/{ if ( FNR > 1 ) printf "\n" # terminate last OID bu not the first line printf "%s", $0 # start this OID but don't write a new-line yet next } # process other lines that we assume are actually part of previous OID { printf "%s", $0 # continue previous line } # terminate the last OID END{ printf "\n" # terminate last OID }

No comments:

Post a Comment

Please use family friendly language.