使用 boto3 验证 AWS 凭证

新手上路,请多包涵

我正在尝试编写使用许多不同 AWS 密钥的 Python 代码,其中一些可能已经过期。给定一个 AWS 密钥对作为字符串,我需要使用 boto3 检查给定的密钥对是否有效。我宁愿不必做任何事情,比如使用 os.system 来运行

echo "$aws_key_id
$aws_secret_key\n\n" | aws configure

然后阅读 aws list-buckets. 的响应

答案应该类似于

def check_aws_validity(key_id, secret):
    pass

其中 key_idsecret 是字符串。

请注意,这不是 Verifying S3 credentials w/o GET or PUT using boto3 的重复,因为我在 boto3.profile 中没有密钥。

提前致谢!

编辑 根据 John Rotenstein 的回答,我得到了以下功能。

 def check_aws_validity(key_id, secret):
    try:
        client = boto3.client('s3', aws_access_key_id=key_id, aws_secret_access_key=secret)
        response = client.list_buckets()
        return true

    except Exception as e:
        if str(e)!="An error occurred (InvalidAccessKeyId) when calling the ListBuckets operation: The AWS Access Key Id you provided does not exist in our records.":
            return true
        return false

原文由 Plaba 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

这种凭证验证方法确实存在;它是 STS GetCallerIdentity API 调用( boto3 方法文档)。

使用过期的临时凭证:

 >>> import boto3
>>> sts = boto3.client('sts')
>>> sts.get_caller_identity()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jantman/venv/lib/python3.8/site-packages/botocore/client.py", line 276, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/home/jantman/venv/lib/python3.8/site-packages/botocore/client.py", line 586, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the GetCallerIdentity operation: The security token included in the request is expired

使用无效凭据:

 >>> import boto3
>>> sts = boto3.client('sts')
>>> sts.get_caller_identity()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jantman/venvs/current/lib/python3.8/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/home/jantman/venvs/current/lib/python3.8/site-packages/botocore/client.py", line 626, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid

使用有效凭据(ID 替换为 X):

 >>> import boto3
>>> sts = boto3.client('sts')
>>> sts.get_caller_identity()
{'UserId': 'AROAXXXXXXXXXXXXX:XXXXXXX', 'Account': 'XXXXXXXXXXXX', 'Arn': 'arn:aws:sts::XXXXXXXXXXXX:assumed-role/Admin/JANTMAN', 'ResponseMetadata': {'RequestId': 'f44ec1d9-XXXX-XXXX-XXXX-a26c85be1c60', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'f44ec1d9-XXXX-XXXX-XXXX-a26c85be1c60', 'content-type': 'text/xml', 'content-length': '426', 'date': 'Thu, 28 May 2020 10:45:36 GMT'}, 'RetryAttempts': 0}}

无效的凭据将引发异常而有效的凭据不会,因此您可以执行以下操作:

 import boto3
sts = boto3.client('sts')
try:
    sts.get_caller_identity()
    print("Credentials are valid.")
except boto3.exceptions.ClientError:
    print("Credentials are NOT valid.")

原文由 Jason Antman 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以通过直接指定凭据来拨打电话:

 import boto3

client = boto3.client('s3', aws_access_key_id='xxx', aws_secret_access_key='xxx')
response = client.list_buckets()

然后您可以使用响应来确定凭据是否有效。

但是,用户可能具有有效凭据,但无权调用 list_buckets() 。这可能会使确定他们是否具有有效凭据变得更加困难。您需要尝试各种组合以查看将什么响应发送回您的代码。

原文由 John Rotenstein 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进