|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import datetime |
| 4 | +import os |
| 5 | +import glob |
| 6 | + |
| 7 | +# Backup configuration |
| 8 | +file_to_backup = "/root/handbook.docx" |
| 9 | +backup_folder = '/media/BackupDrive/handbook/' |
| 10 | +script_file_name = "handbook_backup.py" |
| 11 | +max_backups = 10 |
| 12 | + |
| 13 | +def read_file(): |
| 14 | + global file_to_backup |
| 15 | + |
| 16 | + with open(file_to_backup, 'rb') as handbook: |
| 17 | + return handbook.read() |
| 18 | + |
| 19 | +def write_file(data): |
| 20 | + time = datetime.datetime.now() |
| 21 | + backup_filename = "backup_{:02d}-{:02d}_{:02d}:{:02d}:{:02d}.docx".format( |
| 22 | + time.day, time.month, time.hour, time.minute, time.second |
| 23 | + ) |
| 24 | + backup_path = os.path.join(backup_folder, backup_filename) |
| 25 | + |
| 26 | + with open(backup_path, 'wb') as handbook_backup: |
| 27 | + handbook_backup.write(data) |
| 28 | + print(f"Backup created: {backup_path}") |
| 29 | + |
| 30 | +def clean_old_backups(): |
| 31 | + global script_file_name |
| 32 | + |
| 33 | + # Get a list of all backup files in the directory, sorted by modification time (oldest first) |
| 34 | + backups = sorted( |
| 35 | + glob.glob(os.path.join(backup_folder, "backup_*.docx")), |
| 36 | + key=os.path.getmtime |
| 37 | + ) |
| 38 | + |
| 39 | + # Ensure that the backup script itself is not included in the list |
| 40 | + backups = [f for f in backups if os.path.basename(f) != [script_file_name] |
| 41 | + |
| 42 | + # If there are more backups than max_backups, delete the oldest ones |
| 43 | + if len(backups) > max_backups: |
| 44 | + for backup_to_delete in backups[:-max_backups]: |
| 45 | + os.remove(backup_to_delete) |
| 46 | + print(f"Deleted old backup: {backup_to_delete}") |
| 47 | + |
| 48 | +def main(): |
| 49 | + handbook_data = read_file() |
| 50 | + write_file(handbook_data) |
| 51 | + clean_old_backups() |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + main() |
0 commit comments