python - 如何使用 Python 中的 ElementTree 从特定供应商的 XML 格式的 nmap 输出中获取 IP 地址

标签 python xml xpath nmap

使用 nmap 的 XML 输出对于在主机上运行的可访问虚拟机 - 通过 nmap -oX output.xml -sP 192.168.2.* 获得,我想获取供应商匹配的每台机器的 IP 地址 QEMU 虚拟网卡。我选择使用 Python 的 ElementTree XML API这样做,但我无法将 host 元素与指定的 address 元素隔离。

这是要使用的 XML 输出片段:

<host><status state="up" reason="arp-response"/>
<address addr="192.168.2.93" addrtype="ipv4"/>
<address addr="52:54:00:E2:17:31" addrtype="mac" vendor="QEMU Virtual NIC"/>
<hostnames>
</hostnames>
<times srtt="1023" rttvar="5000" to="100000"/>
</host>
<host><status state="up" reason="arp-response"/>
<address addr="192.168.2.96" addrtype="ipv4"/>
<address addr="52:54:00:45:86:8A" addrtype="mac" vendor="QEMU Virtual NIC"/>
<hostnames>
</hostnames>
<times srtt="155" rttvar="5000" to="100000"/>
</host>
<host><status state="up" reason="arp-response"/>
<address addr="192.168.2.103" addrtype="ipv4"/>
<address addr="52:54:00:61:7A:E5" addrtype="mac" vendor="QEMU Virtual NIC"/>
<hostnames>
</hostnames>
<times srtt="391" rttvar="5000" to="100000"/>
</host>

使用 findall 和下面的 XPath 语法,我可以找到具有所需供应商属性的 address 元素:

import xml.etree.ElementTree as ET
tree = ET.parse('output.xml')
tree.findall("./host/address/[@vendor='QEMU Virtual NIC']")

但我真正想要的是拥有上面找到的 address 元素的 host 元素,这样我就可以找到其他 address 子元素-同一主机的“ipv4”类型的元素,因此我最终可以获得主机 IP 地址。谁能指出我使用 XPathElementTree 实现这一目标的正确方向?

最佳答案

如果你必须使用 ElementTree(而不是 lxml)

>>> [i.get('addr') for i in tree.findall(
...     './host/address[@vendor="QEMU Virtual NIC"]/../address[@addrtype="ipv4"]')]
['192.168.2.93', '192.168.2.96', '192.168.2.103']

lxml 是一个更好的库,但如果不允许外部依赖,则必须这样做。

关于python - 如何使用 Python 中的 ElementTree 从特定供应商的 XML 格式的 nmap 输出中获取 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22311156/

相关文章:

xml - XML Schema 中的集合

dynamic - Selenium 获取动态 ID XPath

python - 从表中提取行

python - 通过 SleekXMPP 发送 facebook 消息

python - matplotlib locator_params 或 set_major_locator 不工作

java - 从 server.xml 按名称读取变量

python - 通过 Python API 在 Blender 中选择一个面并挤出一个立方体

从 MySQL Workbench 导出 EER 图的 XML

javascript - xpath 无法识别标签

python - 使用selenium和python通过CssSelector的 "begins with"方法定位元素