调用GetBucketPolicyStatus操作时,boto3 s3 api因“(NoSuchBucketPolicy)而失败

2024-04-25 19:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我第一次和boto3玩。我想循环使用s3存储桶填充的数组,然后获取每个存储桶的策略状态,尽管我得到了一个错误,但不确定原因。它适用于数组的第一个索引,但之后会出错。为什么?

#!/usr/bin/python3

import boto3

all_buckets=[]

session = boto3.Session(profile_name='default')
s3 = session.client('s3')

def get_bucket_list():
    for i in s3.list_buckets()['Buckets']:
        all_buckets.append(f'  {i["Name"]}')

get_bucket_list()
for j in all_buckets:
    k = (j.strip())
    policy = s3.get_bucket_policy_status(Bucket=k)
    print(policy)

错误:(注意:对AWS ID的引用不真实)

{'ResponseMetadata': {'RequestId': 'D237HE2EPLFX78KV', 'HostId': 'A23zqZFjzk2qeqkPRn0ano3KBiatr9YoPVB94EFGfh0T/ojbNbOkAyz82hibmijgVox3vTrfGz=', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': 'A23zqZFjzk2qeqkPRn0ano3KBiatr9YoPVB94EFGfh0T/ojbNbOkAyz82hibmijgVox3vTrfGz=', 'x-amz-request-id': 'D237HE2EPLFX78KV', 'date': 'Thu, 04 Mar 2021 00:06:33 GMT', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'PolicyStatus': {'IsPublic': False}}
Traceback (most recent call last):
  File "./test2.py", line 17, in <module>
    policy = s3.get_bucket_policy_status(Bucket=k)
  File "/usr/lib/python3/dist-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/lib/python3/dist-packages/botocore/client.py", line 635, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (NoSuchBucketPolicy) when calling the GetBucketPolicyStatus operation: The bucket policy does not exist

Tags: nameinclientgets3bucketusrpolicy
1条回答
网友
1楼 · 发布于 2024-04-25 19:41:22

GetBucketPolicy在没有附加策略时引发异常

因此,我们应该捕获异常,因为不是每个bucket都需要一个bucket策略。可以通过bucket策略或IAM策略控制对bucket的访问

以下是修改后的代码:

def get_bucket_list():
    for i in s3.list_buckets()['Buckets']:
        all_buckets.append(f'  {i["Name"]}')

get_bucket_list()
for j in all_buckets:
    k = (j.strip())
    try:
      policy = s3.get_bucket_policy_status(Bucket=k)
      print(policy)
    except s3.exceptions.from_code('NoSuchBucketPolicy'): 
      print("No Bucket Policy for bucket " + k)
    except: 
      print('something else failed')

相关问题 更多 >