-
-
Save jacksonporter/bd1f63355eb6c85732f51dec2e7484bc to your computer and use it in GitHub Desktop.
boto3 aws find all IAM accesskeys details for the account
This file contains hidden or 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
#!/usr/bin/env python | |
import boto3 | |
import datetime | |
import json | |
ACCESS_KEY_LAST_USED_KEY = "AccessKeyLastUsed" | |
KEY = "LastUsedDate" | |
USERS_KEY = "users" | |
NUMBER_OF_KEYS_KEY = "number_of_keys" | |
def main(): | |
resource = boto3.resource("iam") | |
client = boto3.client("iam") | |
current_date_time = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) | |
current_date_time_minus_two_weeks = current_date_time - datetime.timedelta(days=14) | |
number_of_keys = 0 | |
the_info_dict = {USERS_KEY: {}} | |
for user in resource.users.all(): | |
metadata = client.list_access_keys(UserName=user.user_name) | |
if metadata["AccessKeyMetadata"]: | |
for key in user.access_keys.all(): | |
user_name = user.user_name | |
AccessId = key.access_key_id | |
Status = key.status | |
LastUsed = client.get_access_key_last_used(AccessKeyId=AccessId) | |
if Status == "Active": | |
if KEY in LastUsed[ACCESS_KEY_LAST_USED_KEY]: | |
access_key_date = LastUsed[ACCESS_KEY_LAST_USED_KEY][KEY] | |
if (access_key_date.timestamp() - current_date_time_minus_two_weeks.timestamp()) > 0: | |
if user_name not in the_info_dict[USERS_KEY]: | |
the_info_dict[USERS_KEY][user_name] = {} | |
the_info_dict[USERS_KEY][user_name].update({AccessId: access_key_date.timestamp()}) | |
number_of_keys = number_of_keys + 1 | |
the_info_dict[NUMBER_OF_KEYS_KEY] = number_of_keys | |
with open("output.json", "w") as output: | |
json.dump(the_info_dict, output) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment