You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将Prowler输出转换为字典并生成JSON文件?

我来帮你搞定把Prowler输出转换成字典再导出为JSON文件的需求!咱们一步一步来,先把非结构化的文本解析成结构化的字典,再转成JSON格式。

第一步:解析Prowler输出到Python字典

首先得把你的Prowler输出文本拆分成有意义的结构:比如大章节(像「身份与访问管理」)作为顶层键,下面的子检查项(1.1、1.2)作为子条目,每个条目包含检查标题和对应的信息。

直接给你写好可运行的Python代码,你可以直接用:

import json

# 把你的Prowler输出复制到这里
prowler_output = """0.1 生成AWS IAM凭证报告...
1 身份与访问管理
****************************************
1.1 避免使用root账户(已评分)。
信息!root账户最后访问时间(password key_1 key_2):1970-01-01 00:00:00 N/A N/A
1.2 确保所有拥有控制台密码的IAM用户均启用多因素认证(MFA)(已评分)。"""

# 初始化结果字典
prowler_dict = {
    "metadata": [],
    "checks": {}
}

current_section = None
current_check = None

# 逐行处理文本
for line in prowler_output.splitlines():
    line = line.strip()
    if not line:
        continue
    # 处理元信息行(比如开头的生成报告提示)
    if line.startswith("0."):
        prowler_dict["metadata"].append(line)
        continue
    # 处理分隔线(直接跳过)
    if line.startswith("*"):
        continue
    # 处理大章节(比如「1 身份与访问管理」)
    if line[0].isdigit() and " " in line and not "." in line.split(" ")[0]:
        section_num, section_name = line.split(" ", 1)
        current_section = section_name
        prowler_dict["checks"][current_section] = []
        continue
    # 处理子检查项(比如「1.1 避免使用root账户(已评分)。」)
    if "." in line.split(" ")[0]:
        check_id, check_title = line.split(" ", 1)
        current_check = {
            "id": check_id,
            "title": check_title.strip("."),
            "info": []
        }
        prowler_dict["checks"][current_section].append(current_check)
        continue
    # 处理检查项的信息行(比如「信息!root账户最后访问时间...」)
    if line.startswith("信息!"):
        if current_check:
            current_check["info"].append(line[3:])  # 去掉开头的「信息!」

第二步:将字典导出为JSON文件

解析完字典后,直接用Python的json模块把它写入文件:

# 写入JSON文件,保证中文显示正常,格式缩进美观
with open("prowler_results.json", "w", encoding="utf-8") as f:
    json.dump(prowler_dict, f, ensure_ascii=False, indent=4)

最终的JSON结构示例

运行上面的代码后,你会得到一个结构化的JSON文件,大概长这样:

{
    "metadata": [
        "0.1 生成AWS IAM凭证报告..."
    ],
    "checks": {
        "身份与访问管理": [
            {
                "id": "1.1",
                "title": "避免使用root账户(已评分)",
                "info": [
                    "root账户最后访问时间(password key_1 key_2):1970-01-01 00:00:00 N/A N/A"
                ]
            },
            {
                "id": "1.2",
                "title": "确保所有拥有控制台密码的IAM用户均启用多因素认证(MFA)(已评分)",
                "info": []
            }
        ]
    }
}

如果你的Prowler输出还有更多内容,只需要把文本替换到prowler_output变量里,代码会自动处理其他检查项~

内容的提问来源于stack exchange,提问作者t0sche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:34:39