[英]Verify AWS Credentials with 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_id
和secret
是字符串。
请注意,这不是重复使用 boto3 验证 S3 凭证 w/o GET 或 PUT ,因为我在 boto3.profile 中没有密钥。
提前致谢!
编辑从 John Rotenstein 的回答中,我得到了以下 function 的工作。
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
这种凭证验证方法确实存在; 它是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.")
您可以通过直接指定凭据来拨打电话:
import boto3
client = boto3.client('s3', aws_access_key_id='xxx', aws_secret_access_key='xxx')
response = client.list_buckets()
然后,您可以使用响应来确定凭据是否有效。
但是,用户可能具有有效凭据,但无权调用list_buckets()
。 这可能会使确定他们是否具有有效凭据变得更加困难。 您需要尝试各种组合以查看哪些响应被发送回您的代码。
这是我解决这个问题的方法:
import boto3
import botocore
def check_login():
sts = boto3.client('sts')
try:
sts.get_caller_identity()
return True
except botocore.exceptions.UnauthorizedSSOTokenError:
return False
if check_login():
print("Credentials are valid.")
else:
# do something to log in
与之前答案的区别在于botocore的导入和正确错误(UnauthorizedSSOTokenError)的catch。 它也适用于 Python3(例如要返回的新 boolean 类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.