You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动生成单日AWS CloudTrail事件的CSV文件?

获取AWS CloudTrail单日事件数据的方法

自动化方式(优先推荐)

1. AWS CLI 直接查询

用aws cloudtrail lookup-events命令指定UTC时间范围,就能精准获取单日事件。示例:

# 获取2024年5月20日(UTC)的所有事件,输出为JSON格式并保存到文件
aws cloudtrail lookup-events --start-time 2024-05-20T00:00:00Z --end-time 2024-05-21T00:00:00Z --output json > cloudtrail_20240520.json

如果事件数量超过单次返回上限,需要结合--next-token参数分页获取,或者用--max-items调整单次返回数量。

2. AWS SDK 编程实现

用SDK(比如Python的boto3)可以更灵活地处理数据,适合集成到自动化脚本或定时任务中。示例代码:

import boto3
from datetime import datetime, timedelta
import json

# 初始化CloudTrail客户端
cloudtrail = boto3.client('cloudtrail')

# 定义目标日期(UTC)
target_date = datetime(2024, 5, 20)
start_time = target_date.replace(hour=0, minute=0, second=0)
end_time = start_time + timedelta(days=1)

all_events = []
next_token = None

# 处理分页获取所有事件
while True:
    kwargs = {
        'StartTime': start_time,
        'EndTime': end_time
    }
    if next_token:
        kwargs['NextToken'] = next_token
    
    response = cloudtrail.lookup_events(**kwargs)
    all_events.extend(response['Events'])
    
    next_token = response.get('NextToken')
    if not next_token:
        break

# 将结果写入文件
with open(f'cloudtrail_{target_date.strftime("%Y%m%d")}.json', 'w') as f:
    json.dump(all_events, f, indent=2)

3. 基于S3存储的批量提取

如果已经配置CloudTrail将事件持续投递到S3桶,直接从S3中提取对应日期的日志文件更高效。CloudTrail在S3中的路径格式为AWSLogs/<账户ID>/CloudTrail/<区域>/<年>/<月>/<日>/,可以用AWS CLI批量下载:

# 下载2024年5月20日us-east-1区域的所有日志文件
aws s3 cp s3://your-cloudtrail-bucket/AWSLogs/123456789012/CloudTrail/us-east-1/2024/05/20/ ./daily-logs/ --recursive

手动方式(控制台操作)

如果只是偶尔需要,也可以在CloudTrail控制台的「事件历史」页面,设置时间范围为目标单日,点击「下载事件」选择CSV或JSON格式导出即可。

内容的提问来源于stack exchange,提问作者Tina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 14:45:00