Creating an extremely complex Python script to backup user folders can involve several steps and components, including walking through directories, compressing folders, encryption for security, splitting large backups into manageable chunks, error logging, multi-threading for efficiency, and providing user options via command line arguments. Below is an example script that endeavors to incorporate these features. Please note that this script is for educational purposes and should be tested in a safe, non-critical environment before any real use.
import os
import sys
import shutil
import argparse
from datetime import datetime
import logging
import zipfile
import threading
from cryptography.fernet import Fernet
# Set up logging
logging.basicConfig(filename='backup_log.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Argument Parser setup
parser = argparse.ArgumentParser(description="Complex Backup Utility")
parser.add_argument('source', help="Source directory to backup")
parser.add_argument('destination', help="Destination directory for the backup")
parser.add_argument('--encryption', action='store_true', help="Enable encryption for the backup")
args = parser.parse_args()
def zipdir(path, ziph, chunk_size=500):
"""
Recursively compresses a directory and optionally splits the archive into chunks.
path: directory to compress
ziph: zipfile handle
chunk_size: size in MB before splitting into a new archive part
"""
for root, dirs, files in os.walk(path):
folder = os.path.relpath(root, path)
for file in files:
full_path = os.path.join(root, file)
if os.stat(full_path).st_size > 0:
ziph.write(full_path, os.path.join(folder, file))
if ziph.fp.tell() > chunk_size * 1024 * 1024: # If size exceeds chunk size
ziph.close()
yield
ziph.filename = ziph.filename.replace('.zip', '') + '_part2.zip'
ziph = zipfile.ZipFile(ziph.filename, 'w', zipfile.ZIP_DEFLATED)
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
"""
Encrypts a file using Fernet symmetric encryption.
key: Encryption key
in_filename: Input filename
out_filename: Output filename. If None, '<in_filename>.enc' will be used.
chunksize: Sets the size of the chunk which the function uses to read and encrypt the file.
"""
if not out_filename:
out_filename = in_filename + '.enc'
cipher_suite = Fernet(key)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(cipher_suite.encrypt(chunk))
def backup_directory(source, destination, encrypt=False):
try:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
# Create a backup filename
backup_filename = os.path.join(destination, f'backup_{os.path.basename(source)}_{timestamp}.zip')
zipf = zipfile.ZipFile(backup_filename, 'w', zipfile.ZIP_DEFLATED)
# Start the zipping process
for _ in zipdir(source, zipf):
logging.info(f"Splitting backup into multiple parts. Current part: {zipf.filename}")
zipf.close()
# Encryption
if encrypt:
key = Fernet.generate_key()
key_file = os.path.join(destination, 'backup_key.key')
with open(key_file, 'wb') as keyf:
keyf.write(key)
encrypt_file(key, backup_filename)
os.remove(backup_filename) # Remove the unencrypted backup
logging.info("Backup encrypted successfully.")
logging.info(f"Backup of directory '{source}' completed successfully.")
except Exception as e:
logging.error(f"Error backing up the directory '{source}'. Error: {str(e)}")
if __name__ == "__main__":
backup_directory(args.source, args.destination, args.encryption)
This script incorporates:
- Command-line parsing for user input.
- Recursive directory walking and zipping for backup.
- Optional encryption of the backup using symmetric encryption (Fernet).
- Backup splitting into multiple parts if exceeding a certain size.
- Comprehensive logging for both information and errors.
This example uses the cryptography module for encryption, which you'll need to install (pip install cryptography) if you haven't already.
While this script is "complex," real-world applications may require even more functionality, like database backups, cloud storage options, more sophisticated error handling, configuration file support, and cross-platform compatibility testing. Remember, complexity for its own sake can reduce maintainability and reliability. Always balance complexity against the actual requirements.