Dev*_*aos 3 python command-line-interface amazon-s3 amazon-web-services boto3
您好,我正在尝试使用 python boto3 脚本在帐户中的所有存储桶上打开默认 s3 加密,请参见下文。
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client('s3')
response = s3.list_buckets()
for bucket in response['Buckets']:
enc = s3.get_bucket_encryption(Bucket=bucket['Name'])
s3.put_bucket_encryption(
Bucket=bucket['Name'],
ServerSideEncryptionConfiguration={
'Rules': [
{
'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': 'AES256'
}
},
]
}
)
Run Code Online (Sandbox Code Playgroud)
但我正在努力解决我的代码无法正常工作的问题
给出错误
File "apply.py", line 10, in <module>
enc = s3.get_bucket_encryption(Bucket=bucket['Name'])
File "/Users/hhaqqani/Library/Python/2.7/lib/python/site-packages/botocore/client.py", line 272, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/Users/hhaqqani/Library/Python/2.7/lib/python/site-packages/botocore/client.py", line 576, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ServerSideEncryptionConfigurationNotFoundError) when calling the GetBucketEncryption operation: The server side encryption configuration was not found
Run Code Online (Sandbox Code Playgroud)
您传递了错误的存储桶名称。在您的呼叫中更改Bucket=enc为.Bucket=bucket['Name']put_bucket_encryption
get_bucket_encryption另请注意,如果存储桶实际上未配置加密,则调用将引发异常。虽然这可能看起来很奇怪,但这就是它的工作方式(有关更多详细信息,请参阅boto3/issues/1899 )。因此,要处理这个潜在的异常:
SSECNF = 'ServerSideEncryptionConfigurationNotFoundError'
try:
bucket = client.get_bucket_encryption(Bucket=bucket['Name'])
# check current encryption here, if it's not what you want then update it
# check bucket['ServerSideEncryptionConfiguration']['Rules']
except client.exceptions.ClientError as e:
if e.response['Error']['Code'] == SSECNF:
s3.put_bucket_encryption(...)
else:
print("Unexpected error: %s" % e)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1884 次 |
| 最近记录: |