Last active
June 22, 2022 11:17
-
-
Save andymotta/9bb9b28da3816fbc469e9057435bf802 to your computer and use it in GitHub Desktop.
Find an AWS IAM user corresponding to an AWS Access Key (boto3)
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
# Find the IAM username belonging to the TARGET_ACCESS_KEY | |
import boto3 | |
from botocore.exceptions import ClientError | |
iam = boto3.client('iam') | |
def find_user(key): | |
try: | |
key_info = iam.get_access_key_last_used(AccessKeyId=key) | |
return key_info['UserName'] | |
except ClientError as e: | |
print "Received error: %s", e | |
if e.response['Error']['Code'] == 'AccessDenied': | |
return "Key does not exist in target account" | |
try: | |
print find_user("AKIAXXXXXXXXXXXXXXXX") | |
except ClientError as e: | |
print "Received error: %s", e | |
if e.response['Error']['Code'] == 'ExpiredToken': | |
print "Please login to the target AWS account" |
@robperc Thanks for the heads up, that really speeds up the search. Added UPDATED_find_user_from_access_key.py for a simple example of that
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a heads-up this can be done with a single call using the "get_access_key_last_used" method of the boto3 IAM client.
http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.get_access_key_last_used