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

如何编写Python脚本遍历多个S3存储桶,验证PublicAccessBlockConfiguration所有配置项是否均为TRUE

Check All S3 Buckets for Fully Enabled Public Access Blocks

Got it, let's build out your script to check all buckets instead of just one. Here's a step-by-step solution with full code that fits your needs:

Step 1: Fetch All Your S3 Buckets

First, we need to get the full list of your S3 buckets using list_buckets(). This gives us every bucket name we need to validate.

Step 2: Loop Through Each Bucket & Validate Settings

For each bucket, we'll:

  • Fetch its public access block configuration
  • Handle cases where a bucket has no public access block set (this counts as non-compliant, since all four values aren't set to TRUE)
  • Check if all four required settings are explicitly set to True

Here's the complete, ready-to-run script:

import boto3
from botocore.exceptions import ClientError

def check_s3_public_access_blocks():
    # Initialize the S3 client
    s3 = boto3.client('s3')
    
    # Get the full list of your S3 buckets
    bucket_list_response = s3.list_buckets()
    all_bucket_names = [bucket['Name'] for bucket in bucket_list_response['Buckets']]
    
    non_compliant_buckets = []
    
    for bucket_name in all_bucket_names:
        try:
            # Fetch the public access block config for the current bucket
            pab_config = s3.get_public_access_block(Bucket=bucket_name)['PublicAccessBlockConfiguration']
            
            # Verify ALL four settings are set to True
            all_settings_enabled = (
                pab_config.get('BlockPublicAcls') is True and
                pab_config.get('IgnorePublicAcls') is True and
                pab_config.get('BlockPublicPolicy') is True and
                pab_config.get('RestrictPublicBuckets') is True
            )
            
            if not all_settings_enabled:
                non_compliant_buckets.append(bucket_name)
        
        except ClientError as e:
            # If the bucket has no public access block configured at all, it's non-compliant
            if e.response['Error']['Code'] == 'NoSuchPublicAccessBlockConfiguration':
                non_compliant_buckets.append(bucket_name)
            else:
                # Catch and report other unexpected errors (like permission issues)
                print(f"Unexpected error checking bucket {bucket_name}: {e}")
    
    # Output the final results
    if non_compliant_buckets:
        print("Non-compliant buckets (public access blocks not fully enabled):")
        for bucket in non_compliant_buckets:
            print(f"- {bucket}")
    else:
        print("All buckets have public access blocks fully enabled!")

if __name__ == "__main__":
    check_s3_public_access_blocks()

Key Notes:

  • Exception Handling: We specifically catch the NoSuchPublicAccessBlockConfiguration error—this covers buckets that haven't had any public access block settings applied, which are automatically non-compliant.
  • Strict Validation: We check that all four settings are explicitly True—if any is missing or set to False, the bucket gets added to the non-compliant list.
  • Error Reporting: Any other issues (like missing IAM permissions to read a bucket's config) are printed separately so you can address those edge cases.

Just make sure your AWS credentials are properly configured (via environment variables, ~/.aws/credentials, or an IAM role if running on AWS infrastructure) so the boto3 client can access your S3 resources.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:37:44