Note#2

Recording a Script for One-Click S3 Bucket File Download

Recorded at·Language Chinese -> English·AI Translation
Time CapsuleLong-term valid content

This post was last updated 1 years 10 months ago

The content consists of a standard Python script using the AWS boto3 library, which relies on highly stable APIs and does not contain specific version numbers, dates, or current events.

boto3list_objects_v2
python
import boto3
import os

# Configure AWS credentials and S3 bucket information
aws_access_key_id = 'Your AWS Access Key ID'
aws_secret_access_key = 'Your AWS Secret Access Key'
bucket_name = 'Your S3 Bucket Name'
endpoint_url = 'Your S3 Endpoint URL'

# Create S3 client
s3 = boto3.client(
    's3',
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    endpoint_url=endpoint_url
)

# Get list of all files in the S3 bucket
objects = s3.list_objects_v2(Bucket=bucket_name)

# Create a directory to store downloaded files
download_dir = 'Downloaded Files'
if not os.path.exists(download_dir):
    os.makedirs(download_dir)

# List of font file extensions
font_extensions = ['.ttf', '.otf', '.woff', '.woff2', '.eot']

# Download each file
if 'Contents' in objects:
    for obj in objects['Contents']:
        key = obj['Key']
        file_path = os.path.join(download_dir, key)
        
        # Check if file already exists or is a font file
        if os.path.exists(file_path):
            print(f'Skipping existing file: {file_path}')
            continue
        
        if any(key.lower().endswith(ext) for ext in font_extensions):
            print(f'Skipping font file: {file_path}')
            continue
        
        # Create the directory for the file (if it doesn't exist)
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        
        # Download file
        s3.download_file(bucket_name, key, file_path)
        print(f'Downloaded file: {file_path}')
else:
    print('No files in S3 bucket.')

print('All files downloaded.')