所以我尝试从 MISP 中提取数据,然后将其保存为 csv 文件格式。 我尝试仅拉取一个事件,但已经收到此错误
csv 文件内结果的简短示例。这些代码都存储在一行/一列中
{'id': '1', 'orgc_id': '2', 'org_id': '1', '日期': '2014-10-02', 'threat_level_id': '3', '信息': 'OSINT ShellShock 从 OpenDNS 扫描 IP','已发布':True,'uuid':'542e4c9c-cadc-4f8f-bb11-6d13950d210b','attribute_count':'1067','analysis':'2','timestamp' :'1517817037','分布':'3','proposal_email_lock':False,'锁定':False,'publish_timestamp':'1610092628','sharing_group_id':'0','disable_correlation':False,'extends_uuid' :'','受保护':无,'组织':{'id':'1','名称':'OTISAC','uuid':'02ba0e53-d88e-420f-bd3a-f9150149f4e7','本地' : True}, 'Orgc': {'id': '2', 'name': 'CthulhuSPRL.be', 'uuid': '55f6ea5f-fd34-43b8-ac1d-40cb950d210f', 'local': False}, '属性': [{'id': '1', '类型': '链接', '类别': '外部分析', 'to_ids': False, 'uuid': '542e4cbd-ee78-4a57-bfb8- 1fda950d210b','event_id':'1','分布':'5','时间戳':'1412320445','评论':'','sharing_group_id':'0','删除':False,'disable_correlation ':假,'object_id':'0','object_relation':无,'first_seen':无,'last_seen':无,'value':
所以我现在的问题是,如何重写代码以正确保存数据?
下面是我当前的代码:
# The URL of the MISP instance to connect to
misp_url = 'https://misp.otisac.org/'
# Your MISP authentication key
misp_key = 'qCrtLX4ubnNAnpvFbgHwDf5KhsnDvfIS5HVRvSaM'
# Verify the MISP server's certificate
misp_verifycert = True
from pymisp import PyMISP
import csv
try:
misp = PyMISP(misp_url, misp_key, misp_verifycert)
# Fetch event with ID 1 (modify as needed)
r = misp.search(eventid=[1], metadata=False, pythonify=False)
print("Response:", r) # Debugging statement to understand the structure of the response
# Extract relevant data from the JSON response
event_data = [] # List to store extracted data
for event in r:
event_values = [] # List to store values for each event
for key, value in event.items():
if isinstance(value, list):
# Handle list values (e.g., tags)
value = ','.join(value)
event_values.append(value) # Append extracted data
event_data.append(event_values) # Append values for each event to the main list
# Create CSV header row based on extracted keys
csv_headers = list(r[0].keys())
# Open CSV file for writing
with open('C:\\misp_event_data.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(csv_headers) # Write header row
# Write each event's data as separate rows
writer.writerows(event_data) # Write the extracted event data
print("Event data saved to misp_event_data.csv")
except Exception as e:
print(f"An error occurred: {e}")
看起来您正在将 misp.search() 返回的 json 格式格式化为 csv 格式以导出。实际上,您可以省去一些麻烦,并将您的 misp 搜索调用“return_format”中的属性设置为等于“csv”。这将返回一个准备导出的逗号分隔字符串,而不是您正在使用的 json 格式。默认情况下它会生成一个 json。这将帮助您解决格式问题并节省您一些时间!
这看起来像:
# Fetch event with ID 1 (modify as needed)
r = misp.search(eventid=[1], metadata=False, pythonify=False, return_format='csv')
希望这有帮助!