我正在使用 boto3 在 python 中编写一个脚本来报告过去几个月进行的 api 调用。我的脚本几乎完成了,但我们的最大会话长度为 1 小时,这总是需要比这更长的时间,因此会话到期并且脚本终止。
我试图定期刷新会话以阻止它过期,但我似乎无法让它工作。我真的希望有人以前做过这个并且可以告诉我我做错了什么?
下面是代码的精简版。
import boto3
import datetime
import time
from botocore.exceptions import ClientError
session_start_time = datetime.datetime.now()
start_date = datetime.datetime.now()
start_date -= datetime.timedelta(days=1)
end_date = datetime.datetime.now()
role='arn:aws:iam::1234:role/role'
def role_arn_to_session(**args):
client = boto3.client('sts')
response = client.assume_role(**args)
return boto3.Session(
aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken'])
session = role_arn_to_session(RoleArn=role,RoleSessionName='session')
cloudtrail = session.client('cloudtrail',region_name='us-east-1')
paginator = cloudtrail.get_paginator("lookup_events")
StartingToken = None
page_iterator = paginator.paginate(
PaginationConfig={'PageSize':1000, 'StartingToken':StartingToken },
StartTime=start_date,
EndTime=end_date)
for page in page_iterator:
for ct in page['Events']:
print(ct)
try:
token_file = open("token","w")
token_file.write(page["NextToken"])
StartingToken = page["NextToken"]
except KeyError:
break
if (datetime.datetime.now() - session_start_time).seconds/60 > 10:
page_iterator = None
paginator = None
cloudtrail = None
session = None
session = role_arn_to_session(RoleArn=role,RoleSessionName='session')
cloudtrail = session.client('cloudtrail',region_name='us-east-1')
paginator = cloudtrail.get_paginator("lookup_events")
page_iterator = paginator.paginate(
PaginationConfig={'PageSize':1000, 'StartingToken':StartingToken },
StartTime=start_date,
EndTime=end_date)
session_start_time = datetime.datetime.now()
我很感激这方面的任何帮助。
提前致谢