仅获取具有存储桶策略的 S3 存储桶列表

get only the list of S3 buckets that are having bucket policy

我从下面的 boto 脚本开始:

import boto3
import pprint

from botocore.exceptions import ClientError

boto3.setup_default_session(profile_name='test_terra_profile')

client = boto3.client("s3", region_name='US-EAST-1')

response = client.list_buckets()

print("Listing Amazon S3 Buckets ")

for bucket in response['Buckets']:
    print(f"-- {bucket['Name']}")

我得到了 s3 存储桶的完整列表,其中许多没有存储桶策略。 我是 python 和 boto 的新手,不确定如何使用存储桶策略仅检索 S3? 有没有办法用空桶策略过滤记录? 任何建议将不胜感激。

不幸的是,您将不得不为每个存储桶一个一个地检索策略并自己进行过滤:

import boto3

if __name__ == "__main__":

    client = boto3.client("s3", region_name='us-east-2')
    bucket_list = client.list_buckets()
    buckets_with_policies = []

    for bucket in map(lambda b: b['Name'], bucket_list['Buckets']):
        try:
            print(f'Trying to retrieve policy for bucket {bucket}...')
            policy = client.get_bucket_policy(Bucket=bucket)
            buckets_with_policies.append(bucket)
        except client.exceptions.from_code('NoSuchBucketPolicy'):
            print(f'No policy for {bucket}')

    print(f'Buckets with policies: {buckets_with_policies}')