【发布时间】:2018-12-19 20:48:47
【问题描述】:
我目前正在尝试使用 python 将一些 YAML 转换为 JSON,并且很难正确格式化 JSON。我的 YAML 文件有多个如下所示的文档:
title: Windows Shell Spawning Suspicious Program
status: experimental
description: Detects a suspicious child process of a Windows shell
references:
- https://mgreen27.github.io/posts/2018/04/02/DownloadCradle.html
author: Florian Roth
date: 20018/04/06
logsource:
product: windows
service: sysmon
detection:
selection:
EventID: 1
ParentImage:
- '*\mshta.exe'
- '*\powershell.exe'
- '*\cmd.exe'
- '*\rundll32.exe'
- '*\cscript.exe'
- '*\wscript.exe'
- '*\wmiprvse.exe'
Image:
- '*\schtasks.exe'
- '*\nslookup.exe'
- '*\certutil.exe'
- '*\bitsadmin.exe'
- '*\mshta.exe'
condition: selection
fields:
- CommandLine
- ParentCommandLine
falsepositives:
- Administrative scripts
level: medium
...
我正在尝试为每个文档提取检测、字段、误报和级别,并将它们作为单独的数组放入 JSON 文档中。我的第一次尝试很糟糕,只是将每个文档中的组集中到列表中:
data = {}
data['indicator'] = {}
data['indicator']['detection']=[]
data['indicator']['fields']=[]
data['indicator']['false positives']=[]
data['indicator']['level']=[]
with open(yaml_file, 'r') as yaml_in, open(json_file, 'a') as definition:
loadyaml = yaml.safe_load_all(yaml_in)
for item in loadyaml:
for header, subsections in item.iteritems():
if header == 'detection':
data['indicator']['detection'].append(subsections)
elif header == 'fields':
data['indicator']['fields'].append(subsections)
elif header == 'false positives':
data['indicator']['false positives'].append(subsections)
elif header == 'level':
data['indicator']['level'].append(subsections)
json.dump(data, definition, indent=4)
我希望将我的每个文档作为单独的指标输入到我的 json 文档中,并将它们的检测、字段、dalspositives 和级别都组合在一起——但是我的 python 能力让我失望了。
我将不胜感激!
【问题讨论】:
标签: python json python-2.7 yaml