Created
February 17, 2016 22:23
-
-
Save stevear22/3dfac302c95b015803e5 to your computer and use it in GitHub Desktop.
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
import boto3 | |
from datetime import datetime | |
iam_client = boto3.client('iam') | |
iam_resource = boto3.resource('iam') | |
def get_UsersOlderThan(days): | |
''' Returns list of users whose PasswordLastUsed | |
is greater than <days> ago. | |
''' | |
user_list = [] | |
for user in iam_client.list_users()['Users']: | |
if 'PasswordLastUsed' in user: | |
LastUsed = datetime.strptime(str(user['PasswordLastUsed']), | |
'%Y-%m-%d %H:%M:%S+00:00') | |
if (LastUsed - datetime.today()).days >= days: | |
user_list.append(user['UserName']) | |
return user_list | |
def rotate_Keys(userToRotate): | |
username = iam_resource.User(userToRotate) | |
for oldkey in iam_client.list_access_keys(UserName=userToRotate)['AccessKeyMetadata']: | |
print 'old key:', oldkey['AccessKeyId'] | |
iam_client.update_access_key(UserName=userToRotate, | |
AccessKeyId=oldkey['AccessKeyId'], | |
Status='Inactive') | |
print ' old key deactivated' | |
iam_client.delete_access_key(UserName=userToRotate, | |
AccessKeyId=oldkey['AccessKeyId']) | |
print ' old key deleted\n' | |
access_key_pair = username.create_access_key_pair() | |
print 'NEW KEY GENERATED - PLEASE RECORD THE NEW KEYS' | |
print 'THEY WILL NOT BE DISPLAYED AGAIN' | |
print 'id:', access_key_pair.access_key_id | |
print 'secret:', access_key_pair.secret | |
print 'status:', access_key_pair.status | |
if __name__ == "__main__": | |
users = get_UsersOlderThan(60) | |
print 'users not signed in in the past 60 days:', users, '\n' | |
# UNCOMMENT FOR PRODUCTION: | |
# for user in users: | |
# rotate_Keys(user) | |
# TEST CODE - works only against a user named test | |
rotate_Keys('test') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment