python中xml格式数据的提取

2024-04-26 20:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下xml格式的nmap输出:

<ports><extraports state="closed" count="991">
<extrareasons reason="conn-refused" count="991"/>
</extraports>
<port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="ssh" method="table" conf="3"/></port>
<port protocol="tcp" portid="25"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="smtp" method="table" conf="3"/></port>
<port protocol="tcp" portid="139"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="netbios-ssn" method="table" conf="3"/></port>
<port protocol="tcp" portid="443"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="https" method="table" conf="3"/></port>

我要获取打开的端口号:

print 'Port Number: '+host.find('ports').find('port').get('portid')

但结果只是22。你知道吗

如何获得结果:

22
25
139
443

Tags: nameportconfservicetableopenprotocolmethod
1条回答
网友
1楼 · 发布于 2024-04-26 20:28:06

找到所有port元素,并获得portid属性。你知道吗

使用^{}list comprehension

>>> import xml.etree.ElementTree as ET
>>> root = ET.fromstring('''
<ports><extraports state="closed" count="991">
<extrareasons reason="conn-refused" count="991"/>
</extraports>
<port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="ssh" method="table" conf="3"/></port>
<port protocol="tcp" portid="25"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="smtp" method="table" conf="3"/></port>
<port protocol="tcp" portid="139"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="netbios-ssn" method="table" conf="3"/></port>
<port protocol="tcp" portid="443"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="https" method="table" conf="3"/></port>
</ports>
''')
>>> [port.get('portid') for port in root.findall('.//port')]
['22', '25', '139', '443']

相关问题 更多 >