如何在Boto3中正确使用NextToken解决SecurityHub多账号数据导出问题
问题根因
- 核心逻辑错误导致仅保留最后一页查询结果:代码中已经将所有分页返回的
Findings汇总到了results数组,但循环内每次都用当前页的response覆盖storedata变量,最终写入S3的只有最后一页的查询结果,自然只会展示最后一页对应的账号数据,看起来像随机返回单个账号信息。 - API节流未处理触发TooManyRequestsException:Security Hub的
get_findings接口有请求频率限制,代码没有添加错误重试和请求间隔逻辑,连续分页调用很容易触发节流报错。 - 可选排查项:如果修复代码逻辑后仍无法获取全量账号数据,请确认两点:一是Lambda执行角色的IAM策略包含
securityhub:GetFindings权限且资源配置为*;二是Security Hub管理员账号已完成所有成员账号的关联,且成员账号的安全发现结果已正常同步到管理员账号。
修复后代码
import boto3 import json from botocore.exceptions import ClientError import time import glob client = boto3.client('securityhub') s3 = boto3.resource('s3') # 统一使用全局过滤器,避免前后调用规则不一致 _filter = { 'GeneratorId': [ { 'Value': 'arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark', 'Comparison': 'PREFIX' } ], } def lambda_handler(event, context): all_findings = [] next_token = None # 每次拉取最大100条结果,减少API调用次数 max_results = 100 while True: try: request_params = { "Filters": _filter, "MaxResults": max_results } if next_token: request_params["NextToken"] = next_token response = client.get_findings(**request_params) all_findings.extend(response['Findings']) if 'NextToken' in response: next_token = response['NextToken'] # 增加固定间隔避免触发节流 time.sleep(0.2) else: break except ClientError as e: error_code = e.response['Error']['Code'] if error_code == 'TooManyRequestsException': # 触发节流后等待1秒重试当前页 time.sleep(1) continue raise e # 序列化全部汇总的安全发现结果 output_data = json.dumps(all_findings) print(f"本次共导出{len(all_findings)}条CIS基准安全发现") # 写入本地文件后上传到S3 save_path = "/tmp/SecurityHub-Findings.json" with open(save_path, "w") as f: f.write(output_data) for file_path in glob.glob("/tmp/*"): s3.meta.client.upload_file( file_path, "xxxxx-security-hubfindings", file_path.split('/')[-1] )
内容的提问来源于stack exchange,提问作者Sidin
相关产品推荐
相关产品推荐

