The user wants a script that backs up files to S3, potentially scheduled via cron, while ensuring it handles errors. For incremental backups, I need to check local files against S3. The script should verify if each file is newer or has a different size/ETag. Using head_object to check metadata could be viable. Additionally, I’ll ensure the script accepts parameters like path, bucket, optional prefix, and region. I’m considering adding tqdm for progress tracking, but it's optional.Designing the backup script
I'm creating a Python script, backup_to_s3.py, that will handle backing up files to S3. First, I'll ensure the user installs boto3 with pip install boto3. The script will parse arguments and look something like this:
The needs_upload function checks if the file needs uploading by comparing remote metadata with local files. If --delete is specified, it will also remove local files from S3 that are no longer present. This should keep everything in sync!Implementing the backup and delete logic
For the script, I’ll build a set of keys from the local files and, after uploading, use list_objects_v2 to check for any keys that aren't in the local set. If they aren't present, I’ll delete those objects from S3. I do want to keep it simple and focus on core functionality: mirroring the local directory while skipping unchanged files.
I’ll include prerequisites like installing boto3, configuring AWS credentials, and IAM permissions. I'll also prepare a short intro, installation details, the complete script, and a usage example. Edge cases like directories and hidden files must be handled too.Enhancing backup script functionality
I realize the user might want to back up files both as single files or directories, so I’ll ensure our script can handle both cases and work recursively for directories. For file handling, I’ll use pathlib for ease. I’ll set up logging to track progress, although I could just use print statements for simplicity, as the user may want a quick script.
I’ll make sure to handle exceptions gracefully. In the iter_files function, I’ll yield paths based on whether it’s a file or directory, ensuring the script can adapt to both scenarios smoothly!Adding CLI arguments and structuring the script
I'm implementing command-line interface (CLI) arguments using argparse. The parser will include positional arguments for the source path and bucket, along with optional arguments for prefix, profile, region, delete-extra, and dry-run. I will set defaults where needed.
The function get_s3_client will initialize a boto3 session based on the profile and region, returning an S3 client. I'll make sure to handle exceptions and graceful interruption with KeyboardInterrupt. After writing the code, I’ll include usage instructions for installation and configuration, plus a suggestion for setting up cron jobs for scheduled backups. Let's ensure everything is clear and thorough! Below is a self‑contained Python script that backs up a file or directory to an AWS S3 bucket, skipping files that haven’t changed (incremental backup).
It uses:
boto3 (AWS SDK for Python)
File size + stored mtime in S3 object metadata to decide if upload is needed.
1. Prerequisites
bash
pip install boto3
Configure your AWS credentials (any standard way is fine):
bash
aws configure
# or set AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_PROFILE / AWS_REGION
Ensure the IAM user/role has at least:
s3:PutObject
s3:ListBucket
s3:GetObject
s3:HeadObject
(optionally s3:DeleteObject if you use --delete-extra)
2. Script: backup_to_s3.py
python
3. Basic usage
bash
# Back up directory to S3, under a prefix:
python backup_to_s3.py /home/user/data my-backup-bucket --prefix backups/my-laptop
# Simulate (no changes in S3):
python backup_to_s3.py /home/user/data my-backup-bucket --prefix backups/my-laptop --dry-run
# Mirror directory (remove objects in S3 that no longer exist locally):
python backup_to_s3.py /home/user/data my-backup-bucket --prefix backups/my-laptop --delete-extra
If you want, I can tailor this further (e.g., exclude patterns, logging to a file, encryption, or integration with cron/systemd).
#!/usr/bin/env python3
"""
backup_to_s3.py
Simple incremental backup of a file or directory to an S3 bucket.
Features:
- Recursively uploads a directory (or single file) to S3.
- Skips files that have not changed (based on size + local mtime).
- Preserves local mtime in S3 object metadata for future comparisons.
- Optional dry-run and optional deletion of objects that no longer exist locally.
Usage examples:
python backup_to_s3.py /path/to/data my-bucket
python backup_to_s3.py /path/to/data my-bucket --prefix backups/my-host
python backup_to_s3.py /path/to/file.txt my-bucket --dry-run
python backup_to_s3.py /path/to/data my-bucket --delete-extra
"""
import argparse
import os
import sys
import time
import mimetypes
from pathlib import Path
import boto3
from botocore.exceptions import ClientError
def get_s3_client(profile: str | None, region: str | None):
if profile:
session = boto3.Session(profile_name=profile, region_name=region)
else:
session = boto3.Session(region_name=region)
return session.client("s3")
def iterate_files(source: Path):
"""Yield all files under source (or the file itself if source is a file)."""
if source.is_file():
yield source
else:
for path in source.rglob("*"):
if path.is_file():
yield path
def compute_s3_key(source_root: Path, file_path: Path, prefix: str | None) -> str:
rel = file_path.relative_to(source_root).as_posix()
if prefix:
return f"{prefix.rstrip('/')}/{rel}"
return rel
def needs_upload(
s3_client,
bucket: str,
key: str,
local_path: Path,
) -> bool:
"""
Decide whether a local file needs uploading to S3.
Criteria:
- If object does not exist: upload.
- If ContentLength differs from local file size: upload.
- If stored 'local_mtime' metadata differs from local mtime (int seconds): upload.
"""
try:
resp = s3_client.head_object(Bucket=bucket, Key=key)
except ClientError as e:
code = e.response.get("Error", {}).get("Code", "")
if code in ("404", "NoSuchKey", "NotFound"):
return True
raise
remote_size = resp.get("ContentLength")
remote_mtime = resp.get("Metadata", {}).get("local_mtime")
local_size = local_path.stat().st_size
local_mtime = str(int(local_path.stat().st_mtime))
if remote_size != local_size:
return True
if remote_mtime != local_mtime:
return True
return False
def upload_file(
s3_client,
bucket: str,
key: str,
local_path: Path,
dry_run: bool = False,
):
local_mtime = str(int(local_path.stat().st_mtime))
content_type, _ = mimetypes.guess_type(str(local_path))
extra_args = {
"Metadata": {
"local_mtime": local_mtime,
}
}
if content_type:
extra_args["ContentType"] = content_type
if dry_run:
print(f"[DRY-RUN] Would upload: {local_path} -> s3://{bucket}/{key}")
return
s3_client.upload_file(
Filename=str(local_path),
Bucket=bucket,
Key=key,
ExtraArgs=extra_args,
)
print(f"Uploaded: {local_path} -> s3://{bucket}/{key}")
def list_s3_keys_under_prefix(s3_client, bucket: str, prefix: str | None):
"""List all keys under a given prefix in S3."""
kwargs = {"Bucket": bucket}
if prefix:
kwargs["Prefix"] = prefix.rstrip("/") + "/"
keys = []
continuation_token = None
while True:
if continuation_token:
kwargs["ContinuationToken"] = continuation_token
resp = s3_client.list_objects_v2(**kwargs)
for obj in resp.get("Contents", []):
keys.append(obj["Key"])
continuation_token = resp.get("NextContinuationToken")
if not continuation_token:
break
return keys
def delete_extra_objects(
s3_client,
bucket: str,
prefix: str | None,
local_keys: set[str],
dry_run: bool = False,
):
"""Delete S3 objects under prefix that are not present in local_keys."""
all_remote_keys = list_s3_keys_under_prefix(s3_client, bucket, prefix)
to_delete = [k for k in all_remote_keys if k not in local_keys]
if not to_delete:
return
print(f"Found {len(to_delete)} objects in S3 not present locally.")
if dry_run:
for k in to_delete:
print(f"[DRY-RUN] Would delete: s3://{bucket}/{k}")
return
# Batch deletes in chunks of 1000
chunk_size = 1000
for i in range(0, len(to_delete), chunk_size):
chunk = to_delete[i : i + chunk_size]
delete_payload = {"Objects": [{"Key": k} for k in chunk]}
s3_client.delete_objects(Bucket=bucket, Delete=delete_payload)
for k in chunk:
print(f"Deleted: s3://{bucket}/{k}")
def parse_args():
p = argparse.ArgumentParser(
description="Back up a file or directory to an S3 bucket (incremental)."
)
p.add_argument(
"source",
help="Path to file or directory to back up",
)
p.add_argument(
"bucket",
help="Target S3 bucket name",
)
p.add_argument(
"--prefix",
help="Optional S3 key prefix (e.g. 'backups/my-host')",
default="",
)
p.add_argument(
"--profile",
help="AWS profile name to use (overrides default)",
default=None,
)
p.add_argument(
"--region",
help="AWS region (if not set via env/config)",
default=None,
)
p.add_argument(
"--dry-run",
help="Show what would be uploaded/deleted without actually doing it",
action="store_true",
)
p.add_argument(
"--delete-extra",
help="Delete S3 objects under prefix that no longer exist locally",
action="store_true",
)
return p.parse_args()
def main():
args = parse_args()
source = Path(args.source).expanduser().resolve()
if not source.exists():
print(f"Source does not exist: {source}", file=sys.stderr)
sys.exit(1)
s3_client = get_s3_client(args.profile, args.region)
bucket = args.bucket
prefix = args.prefix or ""
# Determine root for relative paths (so single file still gets just 'filename')
source_root = source if source.is_dir() else source.parent
files = list(iterate_files(source))
print(f"Discovered {len(files)} file(s) under {source}")
uploaded = 0
skipped = 0
local_keys: set[str] = set()
start_time = time.time()
for f in files:
key = compute_s3_key(source_root, f, prefix)
local_keys.add(key)
try:
if needs_upload(s3_client, bucket, key, f):
upload_file(s3_client, bucket, key, f, dry_run=args.dry_run)
uploaded += 1
else:
print(f"Skipped (unchanged): {f} -> s3://{bucket}/{key}")
skipped += 1
except KeyboardInterrupt:
print("\nInterrupted by user.")
sys.exit(1)
except Exception as e:
print(f"Error processing {f}: {e}", file=sys.stderr)
if args.delete_extra:
try:
delete_extra_objects(
s3_client,
bucket=bucket,
prefix=prefix,
local_keys=local_keys,
dry_run=args.dry_run,
)
except Exception as e:
print(f"Error deleting extra objects: {e}", file=sys.stderr)
elapsed = time.time() - start_time
print(
f"\nDone. Uploaded: {uploaded}, Skipped: {skipped}, "
f"Elapsed: {elapsed:.1f}s (dry-run={args.dry_run})"
)
if __name__ == "__main__":
main()