0
import boto
import boto3
from boto.s3.connection import S3Connection
from boto.sts import STSConnection

# Prompt for MFA time-based one-time password (TOTP)
mfa_TOTP = raw_input("Enter the MFA code: ")
role_arn = "arn:aws:iam::123456789012:role/TestOperator"
client = boto3.client('sts')
response = client.assume_role(RoleArn=role_arn,SerialNumber="arn:aws:iam::760787039612:mfa/C34768",RoleSessionName="test",TokenCode=mfa_TOTP)
print response

使用有效的 MFA TokenCode 运行上述代码时,也会出现以下错误

ClientError:调用 AssumeRole 操作时发生错误 (AccessDenied):MultiFactorAuthentication failed with invalid MFA one time pass code。

感谢帮助

4

2 回答 2

0

我解决了 MFA 令牌问题,在我的代码中进行了以下更改

import boto3

role_arn = raw_input("Enter the RoleArn of switch user: ")
SerialNumber = raw_input("Enter the MFA SerialNumber: ")
RoleSessionName = raw_input("Enter the RoleSessionName: ")
mfa_TOTP = raw_input("Enter the MFA code: ")

client = boto3.client('sts')
response = client.assume_role(RoleArn=role_arn,SerialNumber=SerialNumber,RoleSessionName=RoleSessionName,TokenCode=mfa_TOTP)
credentials = response['Credentials']

ec2_resource = boto3.resource('ec2', region,aws_access_key_id = credentials['AccessKeyId'],aws_secret_access_key = credentials['SecretAccessKey'],
                                  aws_session_token = credentials['SessionToken'])
ec2_client = boto3.client('ec2', region,aws_access_key_id = credentials['AccessKeyId'],aws_secret_access_key = credentials['SecretAccessKey'],
                                  aws_session_token = credentials['SessionToken'])

所以现在我们可以使用 ec2_resource 和 ec2_client 对象访问 ec2 资源

谢谢...

于 2018-06-08T06:57:06.780 回答
-1

除非您为此帖子输入随机帐号(这是一个好主意),否则您会忘记在 ARN 中输入真实帐号:

role_arn = "arn:aws:iam::123456789012:role/TestOperator"

应该

role_arn = "arn:aws:iam::760787039612:role/TestOperator"

于 2018-06-07T22:26:40.020 回答