使用 boto3 验证 AWS 凭证

Pla*_*aba 7 amazon-web-services python-3.x boto3

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

echo "$aws_key_id
$aws_secret_key\n\n" | aws configure
Run Code Online (Sandbox Code Playgroud)

然后阅读回复 aws list-buckets.

答案应该看起来像

def check_aws_validity(key_id, secret):
    pass
Run Code Online (Sandbox Code Playgroud)

wherekey_idsecret是字符串。

请注意,这不是使用 boto3 验证没有GET 或 PUT 的 S3 凭据的重复,因为我在 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
Run Code Online (Sandbox Code Playgroud)

Jas*_*man 17

这种凭证验证方法确实存在;它是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
Run Code Online (Sandbox Code Playgroud)

凭据无效:

>>> 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
Run Code Online (Sandbox Code Playgroud)

使用有效凭据(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}}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这里的异常应该是“botocore.exceptions.ClientError”,但如果(例如)拒绝访问 macOS Keychain 凭据,也可能会收到“botocore.exceptions.CredentialRetrievalError”。这将由“client()”调用触发。 (2认同)

Joh*_*ein 7

您可以直接指定凭据进行调用:

import boto3

client = boto3.client('s3', aws_access_key_id='xxx', aws_secret_access_key='xxx')
response = client.list_buckets()
Run Code Online (Sandbox Code Playgroud)

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

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

  • 如果有一个通用的“client.validate_credentials()”函数就好了。 (5认同)