我想解析NMAP XML文件中的特定值。 xml文件的部分看起來像這樣:Python解析NMAP XML輸出「elem key =」NodeList
<nmaprun scanner="nmap" args="nmap -A -P0 -oA scanoutput 192.168.1.5" start="1445258532" startstr="Mon Oct 19 08:42:12 2015" version="6.47" xmloutputversion="1.04">
<hostscript>
<script id="smb-os-discovery" output=" OS: Windows Server 2008 R2 Standard 7601 Service Pack 1 (Windows Server 2008 R2 Standard 6.1) OS CPE: cpe:/o:microsoft:windows_server_2008::sp1 Computer name: SOMEHOSTNAME NetBIOS computer name: SOMEHOSTNAME Domain name: domain.local Forest name: domain.local FQDN: SOMEHOSTNAME.domain.local System time: 2015-10-19T08:50:07-04:00 ">
<elem key="os">Windows Server 2008 R2 Standard 7601 Service Pack 1</elem>
<elem key="lanmanager">Windows Server 2008 R2 Standard 6.1</elem>
<elem key="server">SOMEHOSTNAME\x00</elem>
<elem key="date">2015-10-19T08:50:07-04:00</elem>
<elem key="fqdn">SOMEHOSTNAME.domain.local</elem>
<elem key="domain_dns">domain.local</elem>
<elem key="forest_dns">domain.local</elem>
<elem key="workgroup">HOME\x00</elem>
<elem key="cpe">cpe:/o:microsoft:windows_server_2008::sp1</elem>
</script>
</hostscript>
</nmaprun>
我想從每個鍵的值,但不知道如何解決它。例如,如何從得到的值elem key =「os」?到目前爲止,我可以得到完整的輸出,但是當我將它添加到CSV中時,它會變得雜亂,我需要分別將每個值分開。下面是我的代碼有:
serveros = [script.getAttribute('output') for script in hosttag.getElementsByTagName('script') if script.getAttribute('id') == 'smb-os-discovery']
如果我將其更改爲:
serveros = [script.getElementsByTagName('os') for script in hosttag.getElementsByTagName('script') if script.getAttribute('id') == 'smb-os-discovery']
我得到這個錯誤:
TypeError: sequence item 0: expected string, NodeList found
提前感謝!
是否使用[LXML(http://lxml.de/)模塊?如果是這樣,它允許XPath:'// elem [key ='os']' – Parfait
使用xml.dom.minidom – user1781482
那麼考慮,lxml作爲[minidom](http://stackoverflow.com/questions/12815637/python- minidom-xml-query)受節點和屬性查詢XML的限制。 – Parfait