Last active
February 1, 2024 23:28
-
-
Save adamcousins/6347bee4e842cfed11be85adfc3225dc to your computer and use it in GitHub Desktop.
List Unused Access Keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import datetime | |
from dateutil.tz import tzutc | |
resource = boto3.resource('iam') | |
client = boto3.client('iam') | |
today = datetime.datetime.now() | |
final_report = '' | |
number = 1 | |
# For every user | |
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 | |
# Get User ARN | |
user_arn = client.get_user(UserName=user.user_name) | |
# 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 delta >= 0: | |
final_report += str(number) + " - " + str(delta) + " days" + " " + user_arn['User']['Arn'] + "\n" | |
number += 1 | |
if final_report: | |
with open('output.txt', 'a') as the_file: | |
the_file.write(final_report + '\n') | |
print(final_report); | |
else: | |
print("None"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment