使用CLI从AWS S3下载特定文件列表

5
我想从AWS下载特定文件,已经有了文件URL列表。使用CLI只能使用--recursive命令下载存储桶中的所有文件,但我只想下载我的列表中的文件。您有任何解决方法吗?
4个回答

6

1
谢谢Ryan。然而,在那种情况下,用户的所有文件都具有相同的日期这一共同特征。我的文件没有那个,它们只是S3存储桶中文件的子集,并且我有它们的URL。 - Sara
2
你不必使用 * 属性,可以指定确切的 URL。然后在单个 AWS 语句中使用多个 --includes。我建议您将其包装在 Shell 或 Python 脚本中,使用 boto3 打开您的列表,并创建一个单独的 AWS S3 CP 命令,然后使用 --include 参数为每个 URL 执行该命令。 - RyanWilliamWest
@Sara 你可以使用多个 --include 参数,每个参数指定一个要下载的文件。但是,我认为这并不一定比逐个下载更快,因为此功能需要 AWS CLI 首先扫描现有文件(以适应通配符功能),而复制特定文件只需要一个 API 调用。 - John Rotenstein
谢谢!我最终使用了boto3并循环遍历我的列表。多个--include选项比这个慢。使用aws s3 cp循环遍历该列表也更慢。 - Sara

1

既然您已经有了一个包含S3 URL的文件(例如file.list),如下所示-

s3://bucket/file1
s3://bucket/file2

你可以使用一个简单的bash脚本将所有文件下载到当前工作目录 -
while read -r line;do aws s3 cp "$line" .;done < test.list

7
目前我一直在使用的是这个方法,它有效。但是,这意味着需要针对每行执行aws命令来建立连接等步骤,速度很慢。我想知道是否有更快捷的方式来解决这个问题。 - Sara

0
你可以使用Python的boto3脚本来完成这个任务,你可以按照S3 Bucket的文件结构进行下载。

import boto3
import botocore
import os

# Initialize the S3 client
aws_access_key_id = 'AWSACESSKEY'
aws_secret_access_key = 'AWSSECRETACESSKEY' 
s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)

# List of image object keys you want to download
image_keys_to_download = [
"sta10/maths/chapter10.pdf",
"sta11/science/biology/chapter08.pdf",
"data/sta10/class11/scientists/pythagoras"
]

# Destination directory where the images will be downloaded
destination_base_directory = "~/s3-download-class"

# Loop through the list of image keys and download each image while preserving folder structure
for image_key in image_keys_to_download:
    try:
        # Extract the folder structure from the image key
        folder_structure = os.path.dirname(image_key)

        # Create the destination directory including the folder structure
        destination_directory = os.path.join(destination_base_directory, folder_structure)

        # Make sure the destination directory exists
        os.makedirs(destination_directory, exist_ok=True)

        # Get the object from S3 and save it locally while preserving folder structure
        local_file_path = os.path.join(destination_directory, os.path.basename(image_key))
        s3.download_file('class-10-data', image_key, local_file_path) #Add your S3 Bucket name here.
        print(f"Downloaded {image_key}")
    except botocore.exceptions.NoCredentialsError:
        print("AWS credentials not found. Make sure you have configured your credentials.")
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            print(f"Image {image_key} not found in the S3 bucket.")
        else:
            print(f"Error downloading {image_key}: {e}")

print("Download process completed.")

希望通过这个Python脚本,你可以下载具有相同文件夹结构的特定图片。

-3

这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - Muhammad Mohsin Khan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接