How can we fetch IAM users, their groups and policies?

感情迁移 提交于 2019-12-03 08:41:26

Here, I am using boto commands to do four operations -

  1. List all the users
  2. List policy attached to each user
  3. List roles added to each user
  4. List Mfa devices to see if MFA has been configured by User or not (Here I am not checking is MFA is not enabled, but checking if the device has been configured by a user or not.)

Get IAM connection to AWS Account

import boto3
client = boto3.client('iam',aws_access_key_id="XXX",aws_secret_access_key="XXX") 

Getting IAM Users This will print all the usernames. you can customize if you want to print other details as well.

users = client.list_users()
for key in users['Users']:
    print key['UserName']

Getting List of Policy attached to each user

for key in users['Users']:
    List_of_Policies =  client.list_user_policies(UserName=key['UserName'])
    for key in List_of_Policies['PolicyNames']:
        print key['PolicyName']

Getting List of Groups attached to each user

for key in users['Users']:
    List_of_Groups =  client.list_groups_for_user(UserName=key['UserName'])
       for key in List_of_Groups['Groups']:
           print key['GroupName']

Checking if MFA Device is configured or not

for key in users['Users']:
    List_of_MFA_Devices = client.list_mfa_devices(UserName=key['UserName'])
    for key in List_of_MFA_Devices['MFADevices']:
          print key

You can further check if List_of_MFA_Devices['MFADevices'] is empty or not. If empty, then MFA Device is not configured.

If you want to add output as List of Dict where each index will contain dict have value pairs for userName, Groups, Policy, isMFA_flag_configured or not. Use the following code -

import boto3
client = boto3.client('iam',aws_access_key_id="XXXX",aws_secret_access_key="YYY")
users = client.list_users()
user_list = []
for key in users['Users']:
    result = {}
    Policies = []
    Groups=[]

    result['userName']=key['UserName']
    List_of_Policies =  client.list_user_policies(UserName=key['UserName'])

    result['Policies'] = List_of_Policies['PolicyNames']

    List_of_Groups =  client.list_groups_for_user(UserName=key['UserName'])

    for Group in List_of_Groups['Groups']:
        Groups.append(Group['GroupName'])
    result['Groups'] = Groups

    List_of_MFA_Devices = client.list_mfa_devices(UserName=key['UserName'])

    if not len(List_of_MFA_Devices['MFADevices']):
        result['isMFADeviceConfigured']=False   
    else:
        result['isMFADeviceConfigured']=True    
    user_list.append(result)

for key in user_list:
    print key

Output for the above code -

{'userName': 'user1', 'Groups': ['grp1','grp2'], 'Policies':['policy1','policy2], 'isMFADeviceConfigured': False/True}

{'userName': 'user2', 'Groups': ['grp1','grp2'], 'Policies': ['policy1','policy2], 'isMFADeviceConfigured': False/True}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!