我被委托处理一个xml文件,以查找特定元素并将它们导出到csv文件中。
我具体遇到的问题是一些信息被保存在相同的标签中:
<name>text</name>
<value>value</value>
每个名称标签都包含不同的值,我只需要其中一些。我尝试使用以下代码循环遍历文件:
try:
descr = member.find('.//name').text
if descr == 'description':
plugin.append(descr)
except AttributeError:
descr = 'Unknown'
plugin.append(descr)
但它只返回“未知”。
我的整个代码如下(未完成):
import xml.etree.ElementTree as ET
import csv
tree = ET.parse('plugins.xml')
root = tree.getroot()
nessus_out = open('/home/rj/Documents/python/nessus_out.csv', 'w')
csvwriter = csv.writer(nessus_out)
for member in root.findall('nasl'):
plugin = []
id = member.find('script_id').text
plugin.append(id)
name = member.find('script_name').text
plugin.append(name)
family = member.find('script_family').text
plugin.append(family)
#for each in member.iterfind('nasl'):
try:
solution = member.xpath('.//name/text()')
if solution == 'solution':
plugin.append(solution)
except AttributeError:
solution = 'Unknown'
plugin.append(solution)
csvwriter.writerow(plugin)
nessus_out.close()
最终目标是搜索“solution”,并从其标签中获取相应的值。
XML结构如下:
nasl_plugins
nasl_plugins/nasl
nasl_plugins/nasl/filename
nasl_plugins/nasl/script_id
nasl_plugins/nasl/script_name
nasl_plugins/nasl/script_family
nasl_plugins/nasl/attributes/attribute/name
nasl_plugins/nasl/attributes/attribute/value
为丹尼尔:
XML片段:
<nasl>
<filename>fedora_2017-c3149b5fcb.nasl</filename>
<script_id>101028</script_id>
<script_name>Fedora 25 : xen (2017-c3149b5fcb)</script_name>
<script_version>$Revision: 1.5 $</script_version>
<script_copyright>This script is Copyright (C) 2017-2018 Tenable Network Security, Inc.</script_copyright>
<script_family>Fedora Local Security Checks</script_family>
<cves>
<cve>CVE-2017-10911</cve>
<cve>CVE-2017-10912</cve>
<cve>CVE-2017-10913</cve>
<cve>CVE-2017-10915</cve>
<cve>CVE-2017-10916</cve>
<cve>CVE-2017-10917</cve>
<cve>CVE-2017-10918</cve>
<cve>CVE-2017-10919</cve>
<cve>CVE-2017-10920</cve>
<cve>CVE-2017-10923</cve>
</cves>
<bids>
</bids>
<xrefs>
<xref>FEDORA:2017-c3149b5fcb</xref>
<xref>IAVB:2017-B-0074</xref>
</xrefs>
<dependencies>
<dependency>ssh_get_info.nasl</dependency>
</dependencies>
<required_keys>
<key>Host/local_checks_enabled</key>
<key>Host/RedHat/release</key>
<key>Host/RedHat/rpm-list</key>
</required_keys>
<attribute>
<name>plugin_type</name>
<value>local</value>
</attribute>
<attribute>
<name>plugin_modification_date</name>
<value>2018/02/02</value>
</attribute>
<attribute>
<name>stig_severity</name>
<value>I</value>
</attribute>
<attribute>
<name>cvss_base_score</name>
<value>10.0</value>
</attribute>
</attributes>
我需要的是stig_severity、base_cvss_score等数值,因此我会搜索它们并将其移至下一行以获取数值。至于csv格式,我需要每个插件都在同一行上,格式如下:
id,名称,家族,解决方案,描述,概要,基础CVSS分数,插件类型,stig严重性
,然后下一个插件的数值在下一行中。