Skip to content

Instantly share code, notes, and snippets.

@jobbin
Last active July 4, 2016 12:50
Show Gist options
  • Save jobbin/9ffa395dfea9455208eaa14687ac019b to your computer and use it in GitHub Desktop.
Save jobbin/9ffa395dfea9455208eaa14687ac019b to your computer and use it in GitHub Desktop.
Lambda & CloudWatchEvents & Slackで 長期的にログインしていないIAMユーザを検知・通知する ref: http://qiita.com/jobbin/items/21737cc258cf4268b176
$ mkdir ~/check-iam-users
$ sudo pip install slackweb -t ./check-iam-users/
$ cd check-iam-users/ && ls
slackweb slackweb-1.0.5-py2.7.egg-info
$ zip -r src.zip lambda_function.py slackweb
adding: lambda_function.py (deflated 59%)
adding: slackweb/ (stored 0%)
adding: slackweb/__init__.py (deflated 4%)
adding: slackweb/__init__.pyc (deflated 28%)
adding: slackweb/slackweb.py (deflated 60%)
adding: slackweb/slackweb.pyc (deflated 54%)
# -*- coding: utf-8 -*-
from __future__ import print_function
import boto3
import time
import calendar
import slackweb
print('Loading function')
# Webhook
Slack = slackweb.Slack(url="https://hooks.slack.com/services/T0HTZK5S4/******************z5w")
client = boto3.client('iam')
def lambda_handler(event, context):
# Slack Message Attachments
Attachments = []
# 指定した日数以上ログインしていないユーザ
Users = []
# 日数を指定
Days = 90
Interval = 60 * 60 * 24 * Days
print(Interval)
# 現在の時刻を取得
Now = time.time()
print(Now)
UsersList = client.list_users()
for User in UsersList["Users"]:
print(User)
if str(User.get("PasswordLastUsed")) != 'None':
PasswordLastUsedUnixTime = calendar.timegm(User["PasswordLastUsed"].utctimetuple())
print(PasswordLastUsedUnixTime)
if Now - PasswordLastUsedUnixTime > Interval:
Info = {
"UserName" : User['UserName'],
"LastLogin" : str(User['PasswordLastUsed'])
}
Users.append(Info)
print('######################')
if len(Users) != 0:
Attachments = [
{"pretext": str(Days) + "日以上、ログインしていないユーザがあります!"}
]
print(Users)
for User in Users:
print('######################')
print(User["UserName"])
print('######################')
UserName = User["UserName"]
PasswordLastUsed = User["LastLogin"]
Text = "```IAMユーザ: " + UserName + "\n" + \
"LastLogin: " + PasswordLastUsed + "```"
Attachment = {
"text": Text,
"color": "danger",
"mrkdwn_in": ["text"]
}
Attachments.append(Attachment)
else :
Attachments = [
{"pretext": "IAMユーザをログイン状況を確認しました.\n" + \
str(Days) + "日以上、ログインしていないユーザがありません!"}
]
Slack.notify(attachments = Attachments)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment