繁体   English   中英

如何使用 ijson 从 json 文件中提取一组相应的数据?

[英]How can i use ijson to extract a set of corresponding data from json file?

我有一个 json 文件,就像这样:

    {
  "CVE_data_type" : "CVE",
  "CVE_Items" : [ {
    "cve" : {

      "CVE_data_meta" : {
        "ID" : "CVE-2020-0001",
        "ASSIGNER" : "security@android.com"
      },
      ...
      
    "configurations" : {
      "CVE_data_version" : "4.0",
      "nodes" : [ {
        "operator" : "OR",
        "children" : [ ],
        "cpe_match" : [ {
          "vulnerable" : true,
          "cpe23Uri" : "cpe:2.3:o:google:android:8.0:*:*:*:*:*:*:*",
          "cpe_name" : [ ]
        }, {
          "vulnerable" : true,
          "cpe23Uri" : "cpe:2.3:o:google:android:8.1:*:*:*:*:*:*:*",
          "cpe_name" : [ ]
        }]
      } ]
    },
   ...
    "publishedDate" : "2020-01-08T19:15Z",
    "lastModifiedDate" : "2020-01-14T21:52Z"
  }]
}

我想提取 CVE-ID 和相应的 CPE,所以我可以通过 CPE lcoate CVE-ID,这是我的代码

import ijson
import datetime


def parse_json(filename):
    with open(filename, 'rb') as input_file:
        CVEID = ijson.items(input_file, 'CVE_Items.item.cve.CVE_data_meta.ID', )
        for id in CVEID:
            print("CVE id: %s" % id)
        # for prefix, event, value in parser:
        #     print('prefix={}, event={}, value={}'.format(prefix, event, value))

    with open(filename, 'rb') as input_file:
        cpes = ijson.items(input_file, 'CVE_Items.item.configurations.nodes.item.cpe_match.item', )
        for cpe in cpes:
            print("cpe: %s" % cpe['cpe23Uri'])


def main():
    
    parse_json("cve.json")
    end = datetime.datetime.now()
    

if __name__ == '__main__':
    main()

结果:

CVE id: CVE-2020-0633
CVE id: CVE-2020-0631
cpe: cpe:2.3:o:google:android:8.0:*:*:*:*:*:*:*
cpe: cpe:2.3:o:google:android:10.0:*:*:*:*:*:*:*
cpe: cpe:2.3:o:microsoft:windows_10:1607:*:*:*:*:*:*:*
cpe: cpe:2.3:o:microsoft:windows_server_2016:-:*:*:*:*:*:*:*

但是上面这只是提取数据并没有对应关系。

有人可以帮忙吗? 一点帮助将不胜感激。

我认为,如果您需要跟踪 CVE ID 及其相应的 CPE,则需要遍历整个cve项目并提取所需的数据位(因此您只需遍历文件一次)。 内存效率不如原始迭代,但如果CVE_Items中的每个项目都不是太大,那么这不是问题:

with open(filename, 'rb') as input_file:
    for cves in ijson.items(input_file, 'CVE_Items.item')
        cve_id = cve['cve']['CVE_data_meta']['ID']
        cpes = [match
                for node in cve['configurations']['nodes']
                for match in node['cpe_match']]

如果您知道nodes中总是有一个cpe_match元素,那么您可以将最后一个列表理解替换为cve['configurations']['nodes'][0]['cpe_match']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM