#!/usr/bin/env python3
"""
Simple Python script to back up files or directories to AWS S3.
Requirements:
- pip install boto3
- AWS credentials configured (e.g., via `aws configure`, environment variables, or IAM roles).
Usage:
python backup_to_s3.py /local/path/to/backup my-s3-bucket [optional-prefix]
Examples:
python backup_to_s3.py ./myfiles my-backup-bucket backups/
python backup_to_s3.py /home/user/docs my-backup-bucket user-docs/2023/
"""
import argparse
import boto3
import logging
import os
import sys
from pathlib import Path
from botocore.exceptions import ClientError, NoCredentialsError
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def upload_file(s3_client, local_path, bucket, s3_key):
"""Upload a single file to S3."""
try:
s3_client.upload_file(str(local_path), bucket, s3_key)
logger.info(f"Uploaded: {local_path} -> s3://{bucket}/{s3_key}")
except ClientError as e:
logger.error(f"Error uploading {local_path}: {e}")
return False
return True
def backup_to_s3(source_path, bucket, prefix=""):
"""Backup files or directories from source_path to S3 bucket with optional prefix."""
source = Path(source_path)
if not source.exists():
logger.error(f"Source path does not exist: {source_path}")
return False
s3_client = boto3.client('s3')
successful_uploads = 0
failed_uploads = 0
if source.is_file():
# Single file upload
s3_key = f"{prefix.rstrip('/')}/{source.name}" if prefix else source.name
if upload_file(s3_client, source, bucket, s3_key):
successful_uploads += 1
else:
failed_uploads += 1
else:
# Directory recursive upload
for root, dirs, files in os.walk(source):
for file in files:
local_file = Path(root) / file
rel_path = local_file.relative_to(source)
s3_key = f"{prefix.rstrip('/')}/{rel_path}"
if upload_file(s3_client, local_file, bucket, s3_key):
successful_uploads += 1
else:
failed_uploads += 1
logger.info(f"Backup complete: {successful_uploads} successful, {failed_uploads} failed.")
return failed_uploads == 0
def main():
parser = argparse.ArgumentParser(description="Backup files/directories to AWS S3")
parser.add_argument("source", help="Local file or directory path to backup")
parser.add_argument("bucket", help="S3 bucket name")
parser.add_argument("prefix", nargs="?", default="", help="Optional S3 key prefix (e.g., backups/)")
args = parser.parse_args()
try:
if not backup_to_s3(args.source, args.bucket, args.prefix):
sys.exit(1)
except NoCredentialsError:
logger.error("AWS credentials not found. Please configure AWS credentials.")
sys.exit(1)
except Exception as e:
logger.error(f"Unexpected error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
Quick Start
- Install dependencies:
pip install boto3
- Configure AWS: Run
aws configure or set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION env vars.
- Run the script:
- Backup a file:
python backup_to_s3.py ./myfile.txt my-bucket backups/
- Backup a directory:
python backup_to_s3.py ./myfolder my-bucket backups/myfolder/
- Features:
- Handles files and directories recursively.
- Preserves directory structure under the prefix.
- Logs progress and errors.
- Skips non-existent paths and reports failures.
This script is production-ready for basic backups. For large-scale use, consider aws s3 sync or enhancements like multipart uploads, versioning, or encryption. Let me know if you need modifications!