jmp*_*p91 6 python amazon-s3 amazon-web-services boto3
我第一次玩 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)
Run Code Online (Sandbox Code Playgroud)
错误:(注意:对 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
Run Code Online (Sandbox Code Playgroud)
当没有附加策略时,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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1677 次 |
| 最近记录: |