[英]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.