如何使用 boto 检查 AWS 中的根帐户是否启用了 MFA?

How to check whether MFA is enabled for root account in AWS using boto?

我正在处理受信任的顾问,需要检查是否也为根级别启用了 MFA? 它位于 Trusted advisor 仪表板的安全部分。 我在 Python 使用 Boto 工作。

您可以在 IAM 中使用 GetAccountSummary API 调用,它可用作 boto.iam.IAMConnection 中的 get_account_summary 方法调用。

import boto.iam
conn = boto.iam.connect_to_region('us-east-1')
summary = conn.get_account_summary()

这 returns 一本 Python 字典,其中包含有关您帐户的大量信息。具体来说,查明是否启用了 MFA;

if summary['AccountMFAEnabled']:
    # MFA is enabled
else:
    # MFA is not enabled

此答案更新为 boto3,并假定您在 ~/.aws/config 或 ~/.aws/credentials 文件中只配置了一个帐户:

import boto3

client = boto3.client('iam')

if client.get_account_summary()['SummaryMap']['AccountMFAEnabled']:
    root_has_mfa = True
else:
    root_has_mfa = False

如果您更喜欢 get_account_summary returns 的词典,您也可以这样做:

import boto3

client = boto3.client('iam')

summary = client.get_account_summary()['SummaryMap']

if summary['AccountMFAEnabled']:
    root_has_mfa = True
else:
    root_has_mfa = False