使用boto3验证AWS凭证

时间:2018-11-29 22:47:02

标签: python-3.x amazon-web-services boto3

我正在尝试编写使用许多不同的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中没有密钥。

谢谢!

编辑 根据约翰·罗滕斯坦的回答,我可以使用以下功能。

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

2 个答案:

答案 0 :(得分:10)

确实存在这样的凭证验证方法;这是STS GetCallerIdentity API调用(boto3 method docs)。

具有过期的临时凭证:

>>> 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

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

>>> 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.")

答案 1 :(得分:1)

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

import boto3

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

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

但是,用户可能具有有效的凭据,但是没有呼叫list_buckets()的权限。这可能使确定它们是否具有有效凭据变得更加困难。您需要尝试各种组合,以查看将哪些响应发送回您的代码。