【问题标题】:How to write S3 bucket policy to file?如何将 S3 存储桶策略写入文件?
【发布时间】:2018-03-07 21:31:38
【问题描述】:

我想从我拥有的所有 s3 存储桶中提取 s3 存储桶策略,并将它们存储在各自的 .json 文件中。这应该是 json 格式。但是,在我尝试的解决方案中,它将策略与响应元数据一起存储在文件中,而不是 jSOn 格式。

"ResponseMetadata": {"HTTPStatusCode": 200, ...... "content-type": "application/json"}}}

这可以在 python/boto3 中完成吗?这是我的代码。

try:
    s3client = get_s3Client('us-east-1')
    response = s3client.list_buckets()
    if response and response['Buckets']:
        for bucket in response['Buckets']:
            bucketName = bucket['Name']
            print (bucketName)
            policyname = policy_output + '\\' + bucketName + '.json'
            print (policyname)

            response = s3client.get_bucket_policy(
                Bucket=bucketName
            )
            print (response)
            with open(policyname, 'w') as f:
                json.dump(response, f)
                #f.write(response)

【问题讨论】:

    标签: python amazon-web-services amazon-s3 boto3


    【解决方案1】:

    来自 boto3 get_bucket_policy() 的响应是一个字典。您需要检索“策略”元素。

    试试这样的:

    import json
    import boto3
    from botocore.exceptions import ClientError
    
    s3client = boto3.client('s3')
    response = s3client.list_buckets()
    
    if response and response['Buckets']:
        for bucket in response['Buckets']:
            bucketName = bucket['Name']
            print(bucketName)
            policyname = bucketName + '.json'
            print(policyname)
    
            try:
                response = s3client.get_bucket_policy(
                    Bucket=bucketName
                )
                p = response['Policy']
                s = json.dumps(json.loads(p), indent=4)
                with open(policyname, 'w') as f:
                    f.write(s)
            except ClientError as e:
                if e.response['Error']['Code'] == 'NoSuchBucketPolicy':
                    pass
                else:
                    print(e)
    

    【讨论】:

    • 此解决方案效果很好,但它确实将 json 输出到文件中的一行。可以格式化吗?
    • 已修改以包含漂亮的 JSON 打印。
    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2021-03-31
    相关资源
    最近更新 更多