用Python解析CloudTrail日志

用Python解析CloudTrail日志,python,amazon-web-services,aws-lambda,boto3,amazon-cloudtrail,Python,Amazon Web Services,Aws Lambda,Boto3,Amazon Cloudtrail,我正在研究一个lambda函数,它从CloudTrail获取事件并分析它们 我有这个剧本: s3.download_file(bucket, key, download_path) with gzip.open(download_path, "r") as f: data = json.loads(f.read()) print json.dumps(data) for event in data['Rec

我正在研究一个lambda函数,它从CloudTrail获取事件并分析它们

我有这个剧本:

 s3.download_file(bucket, key, download_path)
        with gzip.open(download_path, "r") as f:
            data = json.loads(f.read())
            print json.dumps(data)
            for event in data['Records']:
                if event['eventName'] in event_list:
                    dateEvent = datetime.strptime(event['eventTime'], "%Y-%m-%dT%H:%M:%SZ")
                    for element in event['userIdentity']:
                        for session in element[0]['sessionContext']:
                            username = session['userName']
                            role = session['arn']
我无法从事件中获取
userName
arn
的值。我得到这个错误:

string indices must be integers: TypeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 34, in lambda_handler
for session in element[0]['sessionContext']:
TypeError: string indices must be integers
如何做到这一点?正确的方法是什么

以下是json字符串:

 "userIdentity": {
                "principalId": "aaaaaaaaaaaaaaaaaaaa",
                "accessKeyId": "aaaaaaaaaaaaaaaaaaaaa",
                "sessionContext": {
                    "sessionIssuer": {
                        "userName": "aaaaaaaaaaaaa",
                        "type": "Role",
                        "arn": "arn:aws:iam::aaaaaaaaaaaaaaaaaa:role/aaaaaaa",
                        "principalId": "aaaaaaaaaaaaaaaaaa",
                        "accountId": "aaaaaaaaaaaaaaaaaaa"
                    },
                    "attributes": {
                        "creationDate": "2017-09-14T15:03:08Z",
                        "mfaAuthenticated": "false"
                }
            },
        "type": "AssumedRole",
        "arn": "aaaaaaaaaaaaaaaaaaaaaaaa",
        "accountId": "aaaaaaaaaaaaaaaaaa"
    },

userIdentity
元素可能有也可能没有
sessionContext
元素,因为只有在该事件期间使用临时IAM凭据时,这些元素才存在

没有
sessionContext
userIdentity
元素如下所示:

"userIdentity": {
  "type": "IAMUser",
  "principalId": "AIDAJ45Q7YFFAREXAMPLE",
  "arn": "arn:aws:iam::123456789012:user/Alice",
  "accountId": "123456789012",
  "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
  "userName": "Alice"
}
"userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROAIDPPEZS35WEXAMPLE:AssumedRoleSessionName",
    "arn": "arn:aws:sts::123456789012:assumed-role/RoleToBeAssumed/MySessionName",
    "accountId": "123456789012",
    "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "sessionContext": {
      "attributes": {
        "creationDate": "20131102T010628Z",
        "mfaAuthenticated": "false"
      },
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AROAIDPPEZS35WEXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/RoleToBeAssumed",
        "accountId": "123456789012",
        "userName": "RoleToBeAssumed"
      }
    }
}
但是带有
sessionContext
元素的
userIdentity
如下所示:

"userIdentity": {
  "type": "IAMUser",
  "principalId": "AIDAJ45Q7YFFAREXAMPLE",
  "arn": "arn:aws:iam::123456789012:user/Alice",
  "accountId": "123456789012",
  "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
  "userName": "Alice"
}
"userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROAIDPPEZS35WEXAMPLE:AssumedRoleSessionName",
    "arn": "arn:aws:sts::123456789012:assumed-role/RoleToBeAssumed/MySessionName",
    "accountId": "123456789012",
    "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "sessionContext": {
      "attributes": {
        "creationDate": "20131102T010628Z",
        "mfaAuthenticated": "false"
      },
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AROAIDPPEZS35WEXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/RoleToBeAssumed",
        "accountId": "123456789012",
        "userName": "RoleToBeAssumed"
      }
    }
}
…或者,如果没有角色联合,它甚至可能看起来像这样

"userIdentity": {
    "type": "IAMUser",
    "principalId": "EX_PRINCIPAL_ID",
    "arn": "arn:aws:iam::123456789012:user/Alice",
    "accountId": "123456789012",
    "accessKeyId": "EXAMPLE_KEY_ID",
    "userName": "Alice",
    "sessionContext": {"attributes": {
        "mfaAuthenticated": "false",
        "creationDate": "2014-03-06T15:15:06Z"
    }}
}
回到你的代码:

for element in event['userIdentity']:
    for session in element[0]['sessionContext']:
        username = session['userName']
        role = session['arn']
元素[0]
不存在,因为
sessionContext
不是列表

如果您想获取已使用或假定的用户名和角色ARN,我认为这会起作用。它考虑直接通过
IAMUser
或通过
AssumedRole
完成的事件

user_identity = event['userIdentity']

# check to see if we have a sessionContext[sessionIssuer]
if 'sessionIssuer' in user_identity.get('sessionContext', {}):
    user_name = user_identity['sessionContext']['sessionIssuer']['userName']
    arn = user_identity['sessionContext']['sessionIssuer']['arn']
else:
    user_name = user_identity['userName']
    arn = user_identity['arn']

作为处理循环的一部分:

for event in data['Records']:
    if event['eventName'] in event_list:
        dateEvent = datetime.strptime(event['eventTime'], "%Y-%m-%dT%H:%M:%SZ")
        user_identity = event['userIdentity']

        # check to see if we have a sessionContext[sessionIssuer]
        if 'sessionIssuer' in user_identity.get('sessionContext', {}):
            user_name = user_identity['sessionContext']['sessionIssuer']['userName']
            arn = user_identity['sessionContext']['sessionIssuer']['arn']
        else:
            user_name = user_identity['userName']
            arn = user_identity['arn']

如果打印“会话”,会得到什么?您可能在JSON中处于错误的级别吗?对不起,我误读了错误。您可以打印“元素”吗?