Python Boto3:尝试从AWS S3下载文件时出错

问题描述 投票:1回答:2

Helllo,

我试图从一个非常大的S3存储桶下载所有文件。我这样连接到S3:

client = boto3.client('s3', 
aws_access_key_id=tempCredentials.credentials.access_key,
aws_secret_access_key = tempCredentials.credentials.secret_key,                                 
aws_session_token=tempCredentials.credentials.session_token)

由此,我做:

# This is going to go through and fill in the dictionary with keys 
from the buckets as specified above 
paginator = client.get_paginator("list_objects")
page_iterator = paginator.paginate(Bucket=bucket["Name"])
l = 0
# We are going to have an list that will hold all the keys 
key_list = []
for i in page_iterator:
    c = i["Contents"]
    for j in c:
          key_list.append(j["Key"])
    for j in key_list:
        download(bucket["Name"], j, "/Users/ahussain/Desktop/S3_Scrubber/" + file_name_helper(j), client)

在哪里,我的下载功能如下:

 def download (bucket_name, key, path, client):
    key_name = key 
    print("Dowloading %s..." % str(key))
    client.download_file(bucket_name, key, path)
    print("Download of %s complete!" % str(key))
    return key_name

会发生什么事情,我成功地通过桶并下载了大量的密钥,但一段时间后程序停止下载密钥并给我这个错误:

botocore.exceptions.ClientError: An error occurred (400) when calling the HeadObject operation: Bad Request

我的猜测是我的会话已经过期,因为我使用MFA来访问这个S3,但我不确定。有没有人遇到过这个错误?

python amazon-web-services amazon-s3 boto3
2个回答
1
投票

上面的答案是错误的或过时的。我不确定。您可以增加凭据的持续时间。它们可以持续长达12个小时。最长不是1小时。转到IAM>角色>您指定的角色>编辑会话持续时间。

enter image description here

根据IAM documentation,最大值由最大CLI / API会话持续时间定义,最大值为12小时。

编辑可能会解决您的问题,考虑到您的操作可能需要1个小时以上且不到12个。如果超过12个,请考虑编辑脚本以刷新凭据。说实话,我不知道该怎么做或者是否有可能,但这个SO answer可能会有所帮助,以及docs


0
投票

临时凭证仅在一小时内有效。来自IAM documentation

duration,指定临时安全凭证有效的时间。最小值为15分钟(900秒),最大值(默认值)为1小时(3600秒)。仅当您希望临时凭证在1小时之前到期时,才需要传递此值。

根据一个开放的bug(https://github.com/boto/boto3/issues/443),boto3不支持为长时间运行的操作刷新临时凭证。

因此,如果您的脚本在~1小时后显示错误,则可能是原因。

© www.soinside.com 2019 - 2024. All rights reserved.