Sun, 13 Oct 2013

Dead simple nmap xml file parsing with python .:.permalink.:.

Love nmap but hate the xml output?

Get the output you want via simple parsing the xml file with python in 20 lines or less:

#!/usr/bin/python
import sys
import lxml.objectify

nxml=lxml.objectify.parse(sys.argv[1])
nroot=nxml.getroot()
print("%s: %s"%(nroot.attrib.get("args"), nroot.attrib.get("startstr")))
for nhost in nroot.findall("//*[local-name()='host']"):
       for nname in nhost.hostnames:
              print('\t%s'%(nname.hostname.attrib.get("name")))
       for naddr in nhost.address:
              print('\t\t%s'%(naddr.attrib.get("addr")))
       for nport in nhost.ports.port:
              print('\t\t%s\t%s\t%s\t%s'%(nport.attrib.get("protocol"),
                                      nport.attrib.get("portid"),
                                      nport.state.attrib.get("state"),
                                      nport.service.attrib.get("name")
                                      ))
print(nroot.runstats.finished.attrib.get("summary")) 

Using lxml and it's objectify function it's dead-simple to get a pythonic version of nmap's xml output. Give it a shot with your errant xml files you know you've got laying around. Don't like this format? Simple: change it to what you want ;-]

Posted at: Sun, 13 Oct 2013 | category: /itsec