gpt4 book ai didi

python - boto3 s3 api 失败, "(NoSuchBucketPolicy) when calling the GetBucketPolicyStatus operation"

转载 作者:行者123 更新时间:2023-12-04 12:29:45 24 4
gpt4 key购买 nike

我第一次玩 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

最佳答案

GetBucketPolicy当没有附加策略时抛出异常。
因此,我们应该捕获异常,因为并非每个存储桶都需要有存储桶策略。可以通过存储桶策略或 IAM 策略控制对存储桶的访问。
这是修改后的代码:

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')

关于python - boto3 s3 api 失败, "(NoSuchBucketPolicy) when calling the GetBucketPolicyStatus operation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66466822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com