2021年1月17日日曜日

aws-cliでAWSコンソールのログイン履歴を調べる

 

下記は、CloudTrailからAWSコンソールのログイン履歴を取得するaws-cliのコマンドです。

aws cloudtrail lookup-events \
--max-items 20 \
--lookup-attributes "AttributeKey=EventName,AttributeValue=ConsoleLogin" \
--query Events[].CloudTrailEvent --output text \
| tr "\t" "\n" \
| jq -r '.|[.eventTime,.eventType,.userIdentity.userName,.sourceIPAddress,.userAgent,.responseElements.ConsoleLogin,.additionalEventData.MFAUsed]|@csv'


このコマンドの実行結果(CSV)を、JupyterLab で見たいので以下のようにしてセルに記述してみます。

import io
import pandas as pd
data = !aws cloudtrail lookup-events \
--max-items 20 \
--lookup-attributes "AttributeKey=EventName,AttributeValue=ConsoleLogin" \
--query Events[].CloudTrailEvent --output text \
| tr "\t" "\n" \
| jq -r '.|[.eventTime,.eventType,.userIdentity.userName,.sourceIPAddress,.userAgent,.responseElements.ConsoleLogin,.additionalEventData.MFAUsed]|@csv'
df = pd.read_csv(
    io.StringIO(data.n),
    header=None,
    names=["EventTime", "EventType", "UserName", "SourceIP", "UserAgent", "Response", "MFAUsed"])
print("作成日: ",end="")
!date
df


下図は、JupyterLabの画面表示例です。