Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
使用 Amazon 开发工具包获取具有 Amazon STS 的会话令牌
以下代码示例演示了如何获取具有 Amazon STS 的会话令牌并将其用于执行需要 MFA 令牌的服务操作。
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
通过传递 MFA 令牌获取会话令牌,然后使用令牌列出账户的 Amazon S3 存储桶。
def list_buckets_with_session_token_with_mfa(mfa_serial_number, mfa_totp, sts_client):
"""
Gets a session token with MFA credentials and uses the temporary session
credentials to list Amazon S3 buckets.
Requires an MFA device serial number and token.
:param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
device, this is an Amazon Resource Name (ARN).
:param mfa_totp: A time-based, one-time password issued by the MFA device.
:param sts_client: A Boto3 STS instance that has permission to assume the role.
"""
if mfa_serial_number is not None:
response = sts_client.get_session_token(
SerialNumber=mfa_serial_number, TokenCode=mfa_totp)
else:
response = sts_client.get_session_token()
temp_credentials = response['Credentials']
s3_resource = boto3.resource(
's3',
aws_access_key_id=temp_credentials['AccessKeyId'],
aws_secret_access_key=temp_credentials['SecretAccessKey'],
aws_session_token=temp_credentials['SessionToken'])
print(f"Buckets for the account:")
for bucket in s3_resource.buckets.all():
print(bucket.name)
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。