我正在尝试编写使用多个不同 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_id和secret是字符串。
请注意,这不是使用 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 …Run Code Online (Sandbox Code Playgroud)