首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python解析奇怪的XML?

Python解析奇怪的XML?
EN

Stack Overflow用户
提问于 2017-04-13 23:07:57
回答 2查看 886关注 0票数 2

我有一个奇怪的XML,我正在试图解析,在阅读了这个之后,我仍然有问题。

我试图解析NIST数据库,它只使用XML。这是它的一个样本。

代码语言:javascript
复制
<?xml version='1.0' encoding='UTF-8'?>
<nvd xmlns:scap-core="http://scap.nist.gov/schema/scap-core/0.1" xmlns:cvss="http://scap.nist.gov/schema/cvss-v2/0.2" xmlns:vuln="http://scap.nist.gov/schema/vulnerability/0.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:patch="http://scap.nist.gov/schema/patch/0.1" xmlns="http://scap.nist.gov/schema/feed/vulnerability/2.0" xmlns:cpe-lang="http://cpe.mitre.org/language/2.0" nvd_xml_version="2.0" pub_date="2017-04-12T18:00:08" xsi:schemaLocation="http://scap.nist.gov/schema/patch/0.1 https://scap.nist.gov/schema/nvd/patch_0.1.xsd http://scap.nist.gov/schema/feed/vulnerability/2.0 https://scap.nist.gov/schema/nvd/nvd-cve-feed_2.0.xsd http://scap.nist.gov/schema/scap-core/0.1 https://scap.nist.gov/schema/nvd/scap-core_0.1.xsd">
  <entry id="CVE-2013-7450">
    <vuln:vulnerable-configuration id="http://nvd.nist.gov/">
      <cpe-lang:logical-test operator="OR" negate="false">
        <cpe-lang:fact-ref name="cpe:/a:pulp_project:pulp:2.2.1-1"/>
      </cpe-lang:logical-test>
    </vuln:vulnerable-configuration>
    <vuln:vulnerable-software-list>
      <vuln:product>cpe:/a:pulp_project:pulp:2.2.1-1</vuln:product>
    </vuln:vulnerable-software-list>
    <vuln:cve-id>CVE-2013-7450</vuln:cve-id>
    <vuln:published-datetime>2017-04-03T11:59:00.143-04:00</vuln:published-datetime>
    <vuln:last-modified-datetime>2017-04-11T10:01:04.323-04:00</vuln:last-modified-datetime>
    <vuln:cvss>
      <cvss:base_metrics>
        <cvss:score>5.0</cvss:score>
        <cvss:access-vector>NETWORK</cvss:access-vector>
        <cvss:access-complexity>LOW</cvss:access-complexity>
        <cvss:authentication>NONE</cvss:authentication>
        <cvss:confidentiality-impact>NONE</cvss:confidentiality-impact>
        <cvss:integrity-impact>PARTIAL</cvss:integrity-impact>
        <cvss:availability-impact>NONE</cvss:availability-impact>
        <cvss:source>http://nvd.nist.gov</cvss:source>
        <cvss:generated-on-datetime>2017-04-11T09:43:13.623-04:00</cvss:generated-on-datetime>
      </cvss:base_metrics>
    </vuln:cvss>
    <vuln:cwe id="CWE-295"/>
    <vuln:references xml:lang="en" reference_type="VENDOR_ADVISORY">
      <vuln:source>MLIST</vuln:source>
      <vuln:reference href="http://www.openwall.com/lists/oss-security/2016/04/18/11" xml:lang="en">[oss-security] 20160418 CVE-2013-7450: Pulp &lt; 2.3.0 distributed the same CA key to all users</vuln:reference>
    </vuln:references>
    <vuln:references xml:lang="en" reference_type="VENDOR_ADVISORY">
      <vuln:source>MLIST</vuln:source>
      <vuln:reference href="http://www.openwall.com/lists/oss-security/2016/04/18/5" xml:lang="en">[oss-security] 20160418 Re: CVE request - Pulp &lt; 2.3.0 shipped the same authentication CA key/cert to all users</vuln:reference>
    </vuln:references>
    <vuln:references xml:lang="en" reference_type="VENDOR_ADVISORY">
      <vuln:source>MLIST</vuln:source>
      <vuln:reference href="http://www.openwall.com/lists/oss-security/2016/05/20/1" xml:lang="en">[oss-security] 20160519 Pulp 2.8.3 Released to address multiple CVEs</vuln:reference>
    </vuln:references>
    <vuln:references xml:lang="en" reference_type="PATCH">
      <vuln:source>CONFIRM</vuln:source>
      <vuln:reference href="https://bugzilla.redhat.com/show_bug.cgi?id=1003326" xml:lang="en">https://bugzilla.redhat.com/show_bug.cgi?id=1003326</vuln:reference>
    </vuln:references>
    <vuln:references xml:lang="en" reference_type="PATCH">
      <vuln:source>CONFIRM</vuln:source>
      <vuln:reference href="https://bugzilla.redhat.com/show_bug.cgi?id=1328345" xml:lang="en">https://bugzilla.redhat.com/show_bug.cgi?id=1328345</vuln:reference>
    </vuln:references>
    <vuln:references xml:lang="en" reference_type="VENDOR_ADVISORY">
      <vuln:source>CONFIRM</vuln:source>
      <vuln:reference href="https://github.com/pulp/pulp/pull/627" xml:lang="en">https://github.com/pulp/pulp/pull/627</vuln:reference>
    </vuln:references>
    <vuln:summary>Pulp before 2.3.0 uses the same the same certificate authority key and certificate for all installations.</vuln:summary>
  </entry>
<nvd>

我试着用ET来解析它,但是我得到了一些奇怪的输出.

例如,当我使用这个,

代码语言:javascript
复制
with open('/tmp/nvdcve-2.0-modified 2.xml', 'rt') as f:
    tree = ElementTree.parse(f)
for child in root:
     print child.tag, child.attrib

我的输出是这样的..。

代码语言:javascript
复制
{http://scap.nist.gov/schema/feed/vulnerability/2.0}entry {'id': 'CVE-2007-6759'}

令人困惑的是,如果我想迭代它,我似乎需要这样做。

代码语言:javascript
复制
for child in root.iter('{http://scap.nist.gov/schema/feed/vulnerability/2.0}entry'):

如果我那样做,我就不知道孩子的孩子是什么,也不知道什么。

例如,我试图提取vuln:cve-id,以及每个单独的cvss:base_metrics (得分访问向量)、vuln:summaryvuln:product

基本上,我试图每小时从NIST网站下载"xml流“,并将其更新到本地mysql数据库中,以便在我的环境中执行漏洞评估时也可以进行查询。弄清楚如何迭代这些XML内容是令人费解的。我想尝试将其转换为JSON,但由于没有1:1的XML/JSON转换,这似乎是一个不必要的额外步骤。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-14 04:51:51

是的,带有名称空间的XML必须被处理为有点不同。下面是继续使用ElementTree API的另一个解决方案。

在这个库中使用名称空间时,您可以看到vuln:summary,您需要在根元素的xmlns:vuln属性中查找vuln名称空间,然后将其称为{http://scap.nist.gov/schema/vulnerability/0.4}summary

代码语言:javascript
复制
import xml.etree.ElementTree as ET
tree = ET.parse('nvdcve-2.0-Modified.xml')
root = tree.getroot()
# default namespace is given by xmlns attribute of root element, still must be provided
for entry in root.findall('{http://scap.nist.gov/schema/feed/vulnerability/2.0}entry'):
    product_list = []
    metric_list = []
    # just use the element's id attribute
    id = entry.get('id')

    summary = entry.find('{http://scap.nist.gov/schema/vulnerability/0.4}summary').text

    software = entry.find('{http://scap.nist.gov/schema/vulnerability/0.4}vulnerable-software-list')
    if software is not None:
        for sw in software.findall('{http://scap.nist.gov/schema/vulnerability/0.4}product'):
            product_list.append(sw.text)

    metrics = entry.find('{http://scap.nist.gov/schema/vulnerability/0.4}cvss')
    if metrics is not None:
        for metric in metrics.find('{http://scap.nist.gov/schema/cvss-v2/0.2}base_metrics').findall('*'):
            # we don't know the element name, but can get it with the tag property
            metric_list.append(metric.tag.replace('{http://scap.nist.gov/schema/cvss-v2/0.2}', '') + ': ' + metric.text)

    print(id, summary, product_list, metric_list)
    #save to database!
票数 2
EN

Stack Overflow用户

发布于 2017-04-14 00:08:35

这是一个名称空间的 XML文档。因此,您需要使用节点各自的命名空间来寻址节点。

文档中使用的命名空间在文档的顶部定义,并映射到所谓的名称空间前缀

代码语言:javascript
复制
xmlns="http://scap.nist.gov/schema/feed/vulnerability/2.0"
xmlns:cvss="http://scap.nist.gov/schema/cvss-v2/0.2"
xmlns:vuln="http://scap.nist.gov/schema/vulnerability/0.4"
...

例如,前缀vuln映射到"http://scap.nist.gov/schema/vulnerability/0.4"

没有前缀的节点称为默认名称空间--它适用于所有不使用显式命名空间前缀的节点(比如根节点nvdentry节点)。

因此,您需要使用完全限定的名称空间,或者使用适当的命名空间前缀(在您的代码中,可以映射与解析文档中映射的名称空间不同的名称空间前缀)来处理这些元素。

下面是使用lxml (和XPath表达式)这样做的一个示例:

代码语言:javascript
复制
from lxml import etree

NSMAP = {
    'n': 'http://scap.nist.gov/schema/feed/vulnerability/2.0',
    'cpe-lang': 'http://cpe.mitre.org/language/2.0',
    'cvss': 'http://scap.nist.gov/schema/cvss-v2/0.2',
    'patch': 'http://scap.nist.gov/schema/patch/0.1',
    'scap-core': 'http://scap.nist.gov/schema/scap-core/0.1',
    'vuln': 'http://scap.nist.gov/schema/vulnerability/0.4',
    'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}


def normalized_tag(node):
    return node.tag.replace('{%s}' % node.nsmap[node.prefix], '')


root = etree.parse(open('nvdcve.xml')).getroot()


entries = root.xpath('//n:nvd/n:entry', namespaces=NSMAP)
for entry in entries:
    print "Entry: %r" % entry.attrib['id']

    # CVE ID
    cve_id = entry.xpath('./vuln:cve-id/text()', namespaces=NSMAP)[0]
    print "  CVE ID: %r" % cve_id

    # Base Metrics
    metrics = entry.xpath('./vuln:cvss/cvss:base_metrics/*', namespaces=NSMAP)
    print "  Base Metrics:"
    for metric in metrics:
        metric_name = normalized_tag(metric)
        metric_value = metric.text
        print "    %s: %s" % (metric_name, metric_value)

    # Summary
    summary = entry.xpath('./vuln:summary/text()', namespaces=NSMAP)[0]
    print "  Summary: %s" % summary

    # Products
    products = entry.xpath('./vuln:vulnerable-software-list/vuln:product',
                           namespaces=NSMAP)
    for product in products:
        print "  Product: %s" % product.text

输出:

代码语言:javascript
复制
Entry: 'CVE-2013-7450'
  CVE ID: 'CVE-2013-7450'
  Base Metrics:
    score: 5.0
    access-vector: NETWORK
    access-complexity: LOW
    authentication: NONE
    confidentiality-impact: NONE
    integrity-impact: PARTIAL
    availability-impact: NONE
    source: http://nvd.nist.gov
    generated-on-datetime: 2017-04-11T09:43:13.623-04:00
  Summary: Pulp before 2.3.0 uses the same the same certificate authority key and certificate for all installations.
  Product: cpe:/a:pulp_project:pulp:2.2.1-1

有关XML名称空间的更多信息,请参见lxml教程中的命名空间部分Wikipedia关于XML名称空间的文章

有关XPath语法的更多信息,请参见例如W3Schools Xpath教程中的XPath语法页面。

要使用XPath,在众多的XPath测试人员中摆弄文档也是非常有帮助的。此外,Firefox的Firebug插件或Google检查器允许您为所选元素显示(或者更确切地说是其中之一) XPath。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43403035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档