import os
import sys
import argparse
import logging
import boto3
import botocore
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def get_s3_client():
"""
Initializes the S3 client.
Boto3 automatically picks up credentials from env vars or ~/.aws/credentials.
"""
try:
s3 = boto3.client('s3')
return s3
except Exception as e:
logger.error(f"Failed to initialize S3 client: {e}")
sys.exit(1)
def upload_directory(s3_client, bucket_name, source_dir, s3_prefix):
"""
Recursively uploads a directory to S3.
"""
# Normalize the source directory path
source_dir = os.path.abspath(source_dir)
if not os.path.exists(source_dir):
logger.error(f"Source directory '{source_dir}' does not exist.")
return
logger.info(f"Starting backup from '{source_dir}' to 's3://{bucket_name}/{s3_prefix}'")
# Walk through the local directory
for root, dirs, files in os.walk(source_dir):
for file in files:
local_path = os.path.join(root, file)
# Calculate relative path to maintain directory structure
relative_path = os.path.relpath(local_path, source_dir)
# Replace OS-specific separators with forward slashes for S3
s3_key = os.path.join(s3_prefix, relative_path).replace("\\", "/")
upload_file(s3_client, bucket_name, local_path, s3_key)
def upload_file(s3_client, bucket_name, file_path, s3_key):
"""
Uploads a single file to S3 if it has changed.
"""
try:
# 1. Check file size locally
local_size = os.path.getsize(file_path)
# 2. Check if file exists in S3 and get its metadata
try:
response = s3_client.head_object(Bucket=bucket_name, Key=s3_key)
s3_size = response['ContentLength']
# Skip if file sizes match (Simple check to save bandwidth)
# For production, you might want to check MD5 hashes (ETag)
if local_size == s3_size:
logger.info(f"Skipping (Unchanged): {s3_key}")
return
except ClientError as e:
if e.response['Error']['Code'] != '404':
raise # Re-raise if it's a real error
# If 404, file doesn't exist, so we proceed to upload
# 3. Upload the file
# ExtraArgs can be used to set ContentType, StorageClass (e.g., GLACIER), etc.
s3_client.upload_file(file_path, bucket_name, s3_key)
logger.info(f"Uploaded: {file_path} -> s3://{bucket_name}/{s3_key}")
except Exception as e:
logger.error(f"Failed to upload {file_path}: {e}")
def main():
parser = argparse.ArgumentParser(description="Backup a local directory to AWS S3")
parser.add_argument('source', help="Path to the local source directory")
parser.add_argument('bucket', help="Name of the S3 bucket")
parser.add_argument('--prefix', default="", help="Optional prefix (folder) inside the S3 bucket")
args = parser.parse_args()
s3_client = get_s3_client()
# Start the backup process
upload_directory(s3_client, args.bucket, args.source, args.prefix)
logger.info("Backup finished.")
if __name__ == "__main__":
main()