【发布时间】:2017-08-29 19:17:18
【问题描述】:
如果你愿意的话,考虑一下你有一个默认的 nmap XML 输出的世界。
我专门试图解析出 IP 地址(这里没有问题)和操作系统供应商(这里有问题)。
问题是因为 xml 标签有多个实例以及属性,我不知道如何使用 untangle 语法从也需要索引的标签中提取和属性。
xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 7.40 scan initiated Tue Aug 29 12:45:56 2017 as: nmap -sV -O -oX ./nmap_results.xml 1.2.3.4/24 -->
<nmaprun attributes="">
<scaninfo attributes="" />
<debugging attributes="" />
<host attributes="">
<status attributes="" />
<address attributes="" />
<hostnames>
<hostname attributes="" />
</hostnames>
<ports>
<extraports attributes="">
<extrareasons attributes="" />
</extraports>
<port attributes="">
<state attributes="" />
<service attributes="" />
</port>
<port attributes="">
<state attributes="" />
<service attributes="">
<cpe>stuff</cpe>
<cpe>more stuff</cpe>
</service>
</port>
...
假设我想从端口的第一个实例中提取属性。
在我的 python 中,我会假设它看起来像这样:
#!/bin/env python
import untangle
nmap = untangle.parse('./location/to/results.xml')
alive = int(nmap.nmaprun.runstats.hosts['up'])
count = range(0,alive,1)
for tick in count:
print(nmap.nmaprun.host[tick].ports.port[0, 'attribute'])
这里的问题是 port[0, 'attribute']) 的实例,因为它想要并且需要那个 0 索引,但是我也想提取一些属性。
这里是python错误:
/usr/bin/python2.7 /path/to/my/dot.py
Traceback (most recent call last):
File "/path/to/my/dot.py", line 10, in <module>
print(nmap.nmaprun.host[tick].ports.port[0, 'vendor'])
TypeError: list indices must be integers, not tuple
Process finished with exit code 1
如果我尝试只使用属性名称而不使用索引,我会得到:
/usr/bin/python2.7 /path/to/my/dot.py
Traceback (most recent call last):
File "/path/to/my/dot.py", line 10, in <module>
print(nmap.nmaprun.host[tick].ports.port['vendor'])
TypeError: list indices must be integers, not str
Process finished with exit code 1
如果我只提供索引,我会得到一个包含所有属性的字符串,但我只需要一个。
我做错了什么还是有办法?
【问题讨论】:
-
你能发布一个完整的 XML 文件吗?发布 sn-p 会使测试变得困难。
-
nmap.nmaprun.host[tick].ports.port[0]的类型是什么? -
我在这里上传了一个完整的 xml (pastebin.com/EgguG1Ss)
-
Python 说:
<class 'untangle.Element'> None <type 'NoneType'> -
您是否限制使用 untangle 模块来解析 xml?附言如果你会使用 smth 像:
print(nmap.nmaprun.host[tick].ports.port[0]['portid']呢?
标签: python xml xml-parsing