要求:從 AWS 賬戶中找出未加密的 s3 存盤桶并為其添加標簽。
實施至今
import boto3
from botocore.exceptions import ClientError
# Retrieve the list of existing buckets
s3 = boto3.client('s3')
response = s3.list_buckets()
# Find out unencrypted bucket list
for bucket in response['Buckets']:
try:
enc = s3.get_bucket_encryption(Bucket=bucket["Name"])
except ClientError as e:
if e.response['Error']['Code'] == 'ServerSideEncryptionConfigurationNotFoundError':
print('Bucket with no server-side encryption: %s' % (bucket['Name']))
else:
print("Bucket with unexpected error: %s, unexpected error: %s" % (bucket['Name'], e))
以下行給了我未加密的桶串列:
print('Bucket with no server-side encryption: %s' % (bucket['Name']))
結果:
Bucket with no server-side encryption: xyz1
Bucket with no server-side encryption: xyz2
需要支持以下
我可以獲取未加密的 s3 存盤桶串列,但不確定如何使用exceptpython 代碼的輸出并使用未加密的存盤桶名稱稍后添加標簽。
uj5u.com熱心網友回復:
如果您在 try-catch 之外宣告了一個串列,您可以稍后訪問它
例如
import boto3
from botocore.exceptions import ClientError
#this is our new list
buckets = []
# Retrieve the list of existing buckets
s3 = boto3.client('s3')
response = s3.list_buckets()
# Find out unencrypted bucket list
for bucket in response['Buckets']:
try:
enc = s3.get_bucket_encryption(Bucket=bucket["Name"])
except ClientError as e:
if e.response['Error']['Code'] == 'ServerSideEncryptionConfigurationNotFoundError':
#add the bucket name to our new list
buckets.append(bucket['Name'])
print('Bucket with no server-side encryption: %s' % (bucket['Name']))
else:
print("Bucket with unexpected error: %s, unexpected error: %s" % (bucket['Name'], e))
#now you can use the "buckets" variable and it will contain all the unencrypted buckets
for bucket in buckets:
print(bucket)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/484300.html
