使用nmap的XML输出来获取主机上运行的可访问虚拟机 - 使用nmap -oX output.xml -sP 192.168.2.*
获取,我希望获取供应商匹配的每台计算机的IP地址{ {1}}。我选择使用Python ElementTree XML API来做到这一点,但我在使用指定的地址元素隔离主机元素时遇到问题。
这里有一个要使用的XML输出片段:
QEMU Virtual NIC
使用<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>
和下面的XPath语法,我可以找到具有所需供应商属性的地址元素:
findall
但我真正想要的是拥有上面找到的地址元素的主机元素,因此我可以找到其他地址子-e;类型的元素&#34; ipv4&#34;对于同一主机,我终于可以拥有主机IP地址。任何人都可以指出我使用 XPath 和 ElementTree 来实现这一目标吗?
答案 0 :(得分:3)
如果必须使用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
是一个更好的库,但如果不允许外部依赖,则必须这样做。
答案 1 :(得分:2)
主持人:
./host[address[@vendor="QEMU Virtual NIC"]]
IPv4地址:
./host[address[@vendor="QEMU Virtual NIC"]]/address[@addrtype="ipv4"]/@addr
以lxml
:
>>> from lxml import etree
>>> doc = etree.XML("""<doc><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></doc>""")
>>> doc.xpath('./host[address[@vendor="QEMU Virtual NIC"]]')
[<Element host at 0xb72c0af4>, <Element host at 0xb72c0b1c>, <Element host at 0xb72c0b44>]
>>> doc.xpath('./host[address[@vendor="QEMU Virtual NIC"]]/address[@addrtype="ipv4"]/@addr')
['192.168.2.93', '192.168.2.96', '192.168.2.103']