我正在尝试编写使用许多不同 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
是字符串。
请注意,这不是 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 许可协议
这种凭证验证方法确实存在;它是 STS GetCallerIdentity API 调用( boto3 方法文档)。
使用过期的临时凭证:
使用无效凭据:
使用有效凭据(ID 替换为 X):
无效的凭据将引发异常而有效的凭据不会,因此您可以执行以下操作: