如何将JSON对象密钥写入CSV文件



当前正在编写一个脚本,从在线环境资产列表中查询一些资产信息。这里是输出大量JSON对象数据的脚本。忽略一些未使用的导入。

(注意,tenableIO的方法是pyTenable包的一部分,但只知道它返回JSON对象,所以我不一定需要使用json.load函数。(

from pprint import pprint
from tenable.io import TenableIO
import time
import json
import os
import datetime
import csv
# filter variables to request specific assets from the api
last_month = int(time.time()) - 2629743
source_list = ["AZURE"]
# TenableIO by default uses environmental variables stored locally for api keys
tio = TenableIO()
for asset in tio.exports.assets(sources=source_list, updated_at=last_month):
hostname = asset['hostnames']
ipv4 = asset['ipv4s']
print(hostname, ipv4)

该脚本的大部分内容直接来自关于如何导出资产列表的可维护文档。我正在努力解决的问题是资产JSON数据的输出。

脚本似乎正确地解析了json数据,并按预期返回了以下输出(使用填充名和IP,因为这是私有数据(

['abc123'] ['XX.XX.XX.XX']
['def456'] ['XX.XX.XX.XX']
['ghi789'] ['XX.XX.XX.XX', 'YY.YY.YY.YY', 'ZZ.ZZ.ZZ.ZZ']

如何获取此输出并将其写入csv文件?更具体地说,我如何使列1作为主机名,列2作为ip地址,其中多个值与它们的键一起存储,而不是作为单独的列存储?

即csv:中的表格格式

Hostnames | IP Address
1. abc123 | XX.XX.XX.XX
2. def456 | XX.XX.XX.XX
3. ghi789'| XX.XX.XX.XX
YY.YY.YY.YY
ZZ.ZZ.ZZ.ZZ
4. jkl123 | XX.XX.XX.XX

编辑:

根据请求添加JSON结构:

{
"asset":{
"fqdn":"example.com"
"hostnames":"172.106.217.225"
"uuid":"150dee8f-6090-4a9c-907c-54a1c39ddab0"
"ipv4s":"172.156.65.8"
"operating_system":[...
]
"network_id":"00000000-0000-0000-0000-000000000000"
"tracked":true
}
"output":"The observed version of Google Chrome is :
Chrome/21.0.1180.90"
"plugin":{
"cve":[...
]
"cvss_base_score":9.3
"cvss_temporal_score":6.9
"cvss_temporal_vector":{...
}
"cvss_vector":{...
}
"description":"The version of Google Chrome on the remote host is prior to 48.0.2564.82 and is affected by the foll ..."
"family":"Web Clients"
"family_id":1000020
"has_patch":false
"id":9062
"name":"Google Chrome < 48.0.2564.82 Multiple Vulnerabilities"
"risk_factor":"HIGH"
"see_also":[...
]
"solution":"Update the Chrome browser to 48.0.2564.82 or later."
"synopsis":"The remote host is utilizing a web browser that is affected by multiple vulnerabilities."
"vpr":{...
}
}
"port":{
"port":0
"protocol":"TCP"
}
"scan":{
"completed_at":"2018-12-31T20:59:47Z"
"schedule_uuid":"413765fb-e941-7eea-ca8b-0a79182a2806e1b6640fe8a2217b"
"started_at":"2018-12-31T20:59:47Z"
"uuid":"e2c070ae-ec37-d9ff-f003-2e89b7e5e1ab8af3a9957a077904"
}
"severity":"high"
"severity_id":3
"severity_default_id":3
"severity_modification_type":"NONE"
"first_found":"2018-12-31T20:59:47Z"
"last_found":"2018-12-31T20:59:47Z"
"state":"OPEN"
}

如果将输出写入csv是您想要的,则可以实现python csv模块

import csv
fields = ['Hostnames', 'IP Address']
filename = "myfile.csv"
li1 = [['abc123'],['XX.XX.XX.XX']]
li2 = [['def456'],['XX.XX.XX.XX']]
li3 = [['ghi789'],['XX.XX.XX.XX']]
li4 = [None, ['YY.YY.YY.YY']]
li5 = [None, ['ZZ.ZZ.ZZ.ZZ']]
rows = [li1, li2, li3, li4, li5]
with open(filename, 'w') as csvfile:  
csvwriter = csv.writer(csvfile)   
csvwriter.writerow(fields)
for row in rows:   
csvwriter.writerow(row)

最新更新