Get list of IAM users and their groups, policies
About boto3: The AWS SDK for Python (Boto3) provides a Python API for AWS infrastructure services. Using the SDK for Python, you can build applications on top of Amazon S3, Amazon EC2, Amazon DynamoDB, and more.
Here I am using boto3 commands to get list of IAM users, their groups and policies
- List all the users
- List policy attached to each user
- List roles added to each user
- 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.)
import boto3
import xlwt
from xlwt import Workbook
from env import aws_access_key_id, aws_secret_access_key
if aws_access_key_id and aws_secret_access_key:
client = boto3.client('iam', aws_access_key_id=aws_access_key_id , aws_secret_access_key=aws_secret_access_key)
else:
print("please provide aws_access_key_id and aws_secret_access_key")
users = client.list_users()
# Workbook is created
wb = Workbook()
# add_sheet is used to create sheet.
sheet1 = wb.add_sheet('IAM Deatils')
user_i = 1
user_i2 =0
policy_i = 1
usergroup_i = 2
mfa_i = 3
# Header name style
style = xlwt.easyxf('pattern: pattern solid, fore_colour black;' 'font: colour white, bold True;')
# Excel Header's
sheet1.write(0, 0, "IAM User's", style)
sheet1.write(0, 1, "Policies", style)
sheet1.write(0, 2, "Group's", style)
sheet1.write(0, 3, "MFA status", style)
# Adjusting the width of cloum's
sheet1.col(0).width = 10000
sheet1.col(1).width = 10000
sheet1.col(2).width = 10000
sheet1.col(3).width = 10000
for key in users['Users']:
username = key['UserName']
List_of_Policies = client.list_user_policies(UserName=key['UserName'])
List_of_Groups = client.list_groups_for_user(UserName=key['UserName'])
List_of_managed_user_policies = client.list_attached_user_policies(UserName=key['UserName'])
Check_mfa_status = client.list_mfa_devices(UserName=key['UserName'])
list_of_user_policies = []
list_of_user_groups = []
# Get list of Managed policy
for key in List_of_managed_user_policies['AttachedPolicies']:
list_of_user_policies.append(key['PolicyName'])
# Get list of Inline policy
for key in List_of_Policies['PolicyNames']:
list_of_user_policies.append(key)
# Get list of user Groups
for key in List_of_Groups['Groups']:
list_of_user_groups.append(key['GroupName'])
# Check user MFA enabled or not
if Check_mfa_status['MFADevices']:
mfa_status = True
else:
mfa_status = False
# Adding to excel
sheet1.write(user_i, user_i2, username)
sheet1.write(user_i, policy_i, ','.join(list_of_user_policies))
sheet1.write(user_i, usergroup_i, ','.join(list_of_user_groups))
sheet1.write(user_i, mfa_i, mfa_status)
user_i += 1
wb.save('aws_iam_status.xls')
print("Finished")
Leave a comment