Reputation: 13
I am trying to extract some elements from the following XML file (trimmed down nmap
output):
<?xml version="1.0"?>
<nmaprun>
<host starttime="1381245200" endtime="1381245316">
<address addr="192.168.1.5" addrtype="ipv4"/>
<hostnames>
<hostname name="host1.example.com" type="PTR"/>
</hostnames>
<os>
<osmatch>
<osclass type="general purpose" vendor="Linux" osfamily="Linux" osgen="2.6.X" accuracy="100">
<cpe>cpe:/o:linux:linux_kernel:2.6</cpe>
</osclass>
</osmatch>
</os>
</host>
</nmaprun>
with the following code:
import xml.etree.ElementTree as ET
d = [
{'path': 'address', 'el': 'addr'},
{'path': 'hostnames/hostname', 'el': 'name'},
{'path': 'os/osmatch/osclass', 'el': 'osfamily'}
]
tree = ET.parse('testnmap.xml')
root = tree.getroot()
for i in root.iter('host'):
for h in d:
if i.find(h['path']): print i.find(h['path']).get(h['el'])
else: print "UNKNOWN ", (h['path'])
The idea being to extract the IP, hostname and OS. The output gives me
UNKNOWN address
UNKNOWN hostnames/hostname
Linux
So the innermost path worked (osfamily), while the others (hostname) failed. What should be the proper call to reach them?
Upvotes: 1
Views: 5439
Reputation: 36272
I think the problem is the boolean comparison of i.find(h['path'])
. It checks if that element has children, and it only happens in <osclass>
. You have to check if it's null, comparing to None
, like:
...
e = i.find(h['path'])
if e is not None: print(e.get(h['el']))
...
It yields:
192.168.1.5
host1.example.com
Linux
Upvotes: 1