我正在尝试将以下格式的Prowler输出转换为字典,然后将字典转换为JSON文件。
0.1 Generating AWS IAM Credential Report...
1 Identity and Access Management ****************************************
1.1 Avoid the use of the root account (Scored).
INFO! Root account last accessed (password key_1 key_2): 1970-01-01 00:00:00 N/A N/A
1.2 Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password (Scored)
WARNING! User XXXX has Password enabled but MFA disabled
WARNING! User XXXX has Password enabled but MFA disabled
1.3 Ensure credentials unused for 90 days or greater are disabled (Scored)
WARNING! User "XXXX" has not logged in during the last 90 days
WARNING! User "XXXX" has not logged in during the last 90 days
OK! User "XXXX" found with credentials used in the last 90 days
OK! User "XXXX" found with credentials used in the last 90 days
1.4 Ensure access keys are rotated every 90 days or less (Scored)
WARNING! XXXXXXX has not rotated access key1 in over 90 days
1.5 Ensure IAM password policy requires at least one uppercase letter (Scored)
OK! Password Policy requires upper case
1.6 Ensure IAM password policy require at least one lowercase letter (Scored)
OK! Password Policy requires lower case
在python中,我有这个函数来解析prowler.txt文件,该文件使用正则表达式来查找节标题作为字典的键值,然后在标题匹配后解析文本文件以添加下面的行密钥的值。
def create_master_report(ec2_info):
prowler_file = 'reports/prowler.txt'
findings = {}
with open(prowler_file, 'r') as f:
for line in f:
if re.search('\s\d\.\d\d*\s\s\w', line):
header = line.strip()
findings.update({header: []})
for i in findings:
prowler_findings = []
with open(prowler_file, 'r') as f:
for index, line in enumerate(f, start=1):
if line.strip() == i:
for line in enumerate(f, start=index+1):
if line != r'\\n':
#if re.search('WARNING!', line):
prowler_findings.append(str(line).strip())
if line == r'\\n':
break
findings.update({i: prowler_findings})
report_json['Prowler Results'].update(findings)
with open(master_report, 'w') as outfile:
json.dump(report_json, outfile, sort_keys=True)
但是,我似乎在循环整个文档并添加了比预期更多的关键值。这里的最终目标是从头部后面的行开始解析文档,然后在检测到新行时中断。我认为while循环可以工作,但我似乎无法实现一个循环遍历每一行并打破一个新行。另外,我只想拉入包含'WARNING!'
的行,但我已经注释掉了以便测试基本功能。
任何人都可以提供有关如何执行此操作的任何见解吗?
答案 0 :(得分:0)
您可以在一个循环中执行此操作。对于每一行,如果是标题,则更新当前密钥,否则使用当前密钥在结果中追加行:
findings = {}
key = None
with open('reports/prowler.txt') as f:
for line in f:
if re.search(r'\s\d\.\d\d*\s\s\w', line):
key = line.strip()
findings[key] = []
elif key is not None:
findings[key].append(line)
答案 1 :(得分:0)
还有一个很好的答案。但请注意:
if line == r'\\n':
如果您想匹配(或不匹配)单个回车,则不起作用。应该简单地说:
if line == '\n':