Skip to content

Instantly share code, notes, and snippets.

@andymotta
Last active June 22, 2022 11:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save andymotta/9bb9b28da3816fbc469e9057435bf802 to your computer and use it in GitHub Desktop.
Save andymotta/9bb9b28da3816fbc469e9057435bf802 to your computer and use it in GitHub Desktop.
Find an AWS IAM user corresponding to an AWS Access Key (boto3)
# 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
Copy link

robperc commented Jun 24, 2017

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

@andymotta
Copy link
Author

andymotta commented Aug 7, 2017

@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