python - 在 AWS Lambda 中解析字典响应

标签 python python-3.x amazon-web-services aws-lambda amazon-cloudtrail

我正在尝试创建一个通过 S3 触发器使用 CloudTrail 事件的 AWS Lambda 函数。此功能将在删除 CloudWatch 日志时发出警报。事件:

'eventSource': 'logs.amazonaws.com'

'eventName': 'DeleteLogStream'

需要作为同一事件一起找到。我的事件中有数据,但无法捕获和打印它。

import boto3
import gzip
import json

SNS_TOPIC = "<SNS TOPIC ARN>"
SNS_SUBJECT = "<SUBJECT>"


s3_client = boto3.client('s3')
sns_client = boto3.client('sns')


def handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']

    
    # Fetch logs from S3
    s3_object = s3_client.get_object(
        Bucket=bucket,
        Key=key,
    )

    # Extract file and metadata from gzipped S3 object
    with gzip.open(s3_object['Body'], 'rb') as binaryObj:
        binaryContent = binaryObj.read()
    
    # Convert from binary data to text
    raw_logs = binaryContent.decode()
    
    # Change text into a dictionary
    dict_logs = json.loads(raw_logs)
    

    # Make sure json_logs key 'Records' exists
    if 'Records' in dict_logs.keys():
    
        print("Printing Dictionary Content: {} \n\n".format(dict_logs))
        
	if dict_logs['Records'][0]['eventSource'] == 'logs.amazonaws.com' and dict_logs['Records'][0]['eventName'] == 'DeleteLogStream':
			print("Found DeleteLogStream event from logs.amazonaws.com!")
		
        # Print Key-Value pair for each item found
        for key, value in dict_logs['Records'][0].items():
            # Account for values that are also dictionaries
            if isinstance(value, dict):
                print("Parent Key: {}".format(key))
                for k, v in value.items():
                    print("Subdict Key: {}".format(k))
                    print("Subdict Value: {}".format(v))
                continue
            else:
                print("Key: {}".format(key))
                print("Value: {}".format(value))

        
        alert_message = "The following log was found: <extracted log contents here>"
        
        # Publish message to SNS topic
        sns_response = sns_client.publish(
            TopicArn=SNS_TOPIC,
            Message=alert_message,
            Subject=SNS_SUBJECT,
            MessageStructure='string',
        )

    else:
        print("Records key not found")

这是我得到的结果: Result from Code

我的代码打印键/值以进行调试。知道为什么“DeleteLogStream”和“logs.amazonaws.com”值没有解析出来吗?

示例 json 事件如下: https://raw.githubusercontent.com/danielkowalski1/general-scripts/master/sampleevent

最佳答案

好的,问题解决了。这将遍历整个记录列表,然后筛选每个列表值的字典,从而找到所有出现的“DeleteLogStream”。

EVENT_SOURCE = "logs.amazonaws.com"
EVENT_NAME = "DeleteLogStream"     

# Make sure 'Records'key exists
    if 'Records' in dict_logs.keys():
        for item in dict_logs['Records']:

            # Trigger only if a log
            if ('eventSource' in item):
                if (item['eventSource'] == EVENT_SOURCE):
                    if (item['eventName'] == EVENT_NAME):
                        # Grab other useful details for investigation
                        if item['sourceIPAddress']:
                            src_ip = item['sourceIPAddress']
                        if item['userIdentity']['arn']:
                            src_user = item['userIdentity']['arn']

关于python - 在 AWS Lambda 中解析字典响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878667/

相关文章:

python - 使用 Elastic Beanstalk 上的 Supervisor 在后台运行 Huey 任务队列

python - 应用程序引擎 ListProperty 上的时间不平等过滤器在链接时失败

python - 系列的长度与 np.where 不匹配

python - 如何使用 Python 在 AWS lambda 中设置环境变量

python - 链接回之前访问过的表单

python - 通过python脚本加载fixture.json

python - 在数据框中查找必须包含列表中至少 2 个元素的行

python - 进行可能的组合?

amazon-web-services - 将 Amazon SQS 与多个消费者一起使用

amazon-s3 - 有哪些客户端工具可用于管理 Amazon S3 和 CloudFront?