Skip to content

Instantly share code, notes, and snippets.

@Dmitry1987
Created September 17, 2019 01:05
Show Gist options
  • Save Dmitry1987/cb5336ec184c92232e0fc33426d9cdf6 to your computer and use it in GitHub Desktop.
Save Dmitry1987/cb5336ec184c92232e0fc33426d9cdf6 to your computer and use it in GitHub Desktop.
[Python 3] List last access time of all AWS IAM Users access keys
import boto3
import datetime
from dateutil.tz import tzutc
from os import environ
import pandas as pd
# Init the AWS clients
resource = boto3.resource('iam')
client = boto3.client('iam')
# List keys that did not access AWS for more than X days
DAYS_AGO = environ.get('IAM_LAST_ACCESS_DAYS_AGO', 0)
# For delta of days
today = datetime.datetime.now()
# The dict for pandas table
final_report = {'users':[], 'dates':[]}
# For every user list the last access time
for user in resource.users.all():
# Get Access Keys for the User
keys_response = client.list_access_keys(UserName=user.user_name)
last_access = None
# For every Access Key associate with the user
for key in keys_response['AccessKeyMetadata']:
last_used_response = client.get_access_key_last_used(AccessKeyId=key['AccessKeyId'])
if 'LastUsedDate' in last_used_response['AccessKeyLastUsed']:
accesskey_last_used = last_used_response['AccessKeyLastUsed']['LastUsedDate']
if last_access is None or accesskey_last_used < last_access:
last_access = accesskey_last_used
# More than x days since last access?
if last_access is not None:
delta = (today - last_access.replace(tzinfo=None)).days
if DAYS_AGO == 0:
# Add all last access times of all users
final_report['users'].append(user.user_name)
final_report['dates'].append(f"{str(delta)} days ago")
elif delta >= DAYS_AGO:
# Add only old enough times
final_report['users'].append(user.user_name)
final_report['dates'].append(f"{str(delta)} days ago")
# Show the pretty table of results
df = pd.DataFrame(final_report)
df = df[['users', 'dates']]
print(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment