提醒AWS中的旧访问密钥

时间:2019-02-20 16:58:23

标签: python boto3 amazon-sns

我没有得到原始问题的答案,但是我已经对代码进行了调整,因此我将其保留在这里,以防将来有人试图弄清楚。我是Python的新手,但是可以。这是我为Lambda函数创建的Python脚本,该脚本检查您的AWS账户中的用户并向SNS主题发布通知。我已经安排了一个带有cron表达式的CloudWatch规则来每天运行它。

import boto3, json, time, datetime, sys, re
iam_client = boto3.client('iam')
sns_client = boto3.client('sns')
users = iam_client.list_users()
user_list = []
for key in users['Users']:
    user_list = key['UserName']
    accesskeys = iam_client.list_access_keys(UserName=key['UserName'])
    for items in user_list.split('\n'):
        for key in accesskeys['AccessKeyMetadata']:
            accesskeydate = accesskeys['AccessKeyMetadata'][0]['CreateDate']
            accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
            currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
            accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
            currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())
            active_days = (currentd - accesskeyd)/60/60/24
            message = (key['UserName'],int(round(active_days))),
            message = re.sub(r'[^a-zA-Z0-9 ]', "", str(message))
            message = re.sub(r' ', ' is ', str(message))
            if active_days >= 90:
                sns_client.publish(
                    TopicArn='arn:aws:sns:us-west-2:xxxxxxxxxxxxx:topic-name',
                    Subject='User with Old Access Key Detected',
                    Message="The access key for " + str(message) + " days old. This user access key should be replaced ASAP.",
                )

0 个答案:

没有答案