Skip to content

Instantly share code, notes, and snippets.

@shanedroid
Created May 31, 2017 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanedroid/3368bec22df35c7edc969742a6126902 to your computer and use it in GitHub Desktop.
Save shanedroid/3368bec22df35c7edc969742a6126902 to your computer and use it in GitHub Desktop.
Find the IAM username belonging to a given Access key
#!/usr/bin/env python
## -*- coding: utf-8 -*-
"""Find the IAM username belonging to a given Access key"""
# Taken from David Brodsky's - find_iam_user script
# https://gist.github.com/OnlyInAmerica/9964456
from optparse import OptionParser
import boto.iam, os
def build_opt_parser():
parser = OptionParser(usage="Usage: %prog [options]")
parser.add_option("-k", "--key", dest="key", help="AWS IAM key to search for.")
# parser.add_option("-p", "--profile", dest="profile", help="~/.aws/config profile name. Defaults to default", default="")
return parser
def find_key(users, key):
for user in users:
for key_result in iam.get_all_access_keys(user['user_name'])['list_access_keys_response']['list_access_keys_result']['access_key_metadata']:
aws_access_key = key_result['access_key_id']
if aws_access_key == key:
print 'Target key belongs to:'
print 'user : ' + user['user_name']
return True
return False
def main():
parser = build_opt_parser()
(options, args) = parser.parse_args()
# os.environ["AWS_PROFILE"] = options.profile
if 'AWS_SECRET_KEY' in os.environ: del os.environ['AWS_SECRET_KEY']
if 'AWS_ACCESS_KEY' in os.environ: del os.environ['AWS_ACCESS_KEY']
global iam
iam = boto.connect_iam()
users = iam.get_all_users('/')['list_users_response']['list_users_result']['users']
if not find_key(users, options.key):
print 'Did not find access key (' + options.key + ') in ' + str(len(users)) + ' IAM users.'
if __name__ == "__main__":
main()
@shanedroid
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment