如何在AWS KMS中使用Boto3 download_file?

时间:2015-10-20 14:01:57

标签: python amazon-web-services amazon-s3 boto

我有一个非常简单的脚本,可以从存储桶中下载文件。该文件利用KMS加密密钥,我的策略和角色设置正确但我仍然收到错误。

代码

#!/usr/bin/env python
import boto3
s3_client = boto3.client('s3')
s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt')

错误

Traceback (most recent call last):
  File "./getfile.py", line 4, in <module>
s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt')
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/inject.py", line 91, in download_file
extra_args=ExtraArgs, callback=Callback)
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 659, in download_file
extra_args, callback)
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 674, in _download_file
self._get_object(bucket, key, filename, extra_args, callback)
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 698, in _get_object
extra_args, callback)
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 712, in _do_get_object
**extra_args)
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 301, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 386, in _make_api_call
raise ClientError(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the GetObject operation: Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4.

2 个答案:

答案 0 :(得分:12)

想出来

<强>代码

#!/usr/bin/env python
import boto3
from botocore.client import Config
s3_client = boto3.client('s3', config=Config(signature_version='s3v4'))
s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt')

答案 1 :(得分:5)

您可能还想知道如何使用kms密钥将文件上传到s3。

s3_client = boto3.client('s3', config=Config(signature_version='s3v4'))
s3_client.upload_file(filename, bucketname, objectkey, ExtraArgs={"ServerSideEncryption": "aws:kms", "SSEKMSKeyId": <somekmskeyid>})

如果您不提供kms密钥ID,则默认使用s3 kms主密钥。