56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
from datetime import datetime
|
|
from zipfile import ZipFile
|
|
import os
|
|
import shutil
|
|
|
|
# base directory
|
|
basedir = "/media/hd/cloud"
|
|
|
|
# list of the paths to the files and directories to be copied, relative to the base directory
|
|
filelist = "/media/hd/cloud/Tilman/Computer/selective-backups/filelist.txt"
|
|
|
|
# duration for backups to be kept
|
|
days_to_keep = 5
|
|
months_to_keep = 5
|
|
|
|
# directories to backup to
|
|
daily_dir = "/media/hd/cloud/Tilman/Computer/selective-backups/daily/"
|
|
monthly_dir = "/media/hd/cloud/Tilman/Computer/selective-backups/monthly/"
|
|
|
|
now = datetime.now()
|
|
today = datetime.today()
|
|
target_filename = today.strftime('%Y-%m-%d') + "_selective-backup.zip"
|
|
|
|
with open(filelist) as file:
|
|
lines = [line.rstrip() for line in file]
|
|
|
|
# backup directories and files
|
|
with ZipFile(daily_dir + target_filename, 'w') as zip:
|
|
for line in lines:
|
|
if os.path.isdir(basedir + line):
|
|
for root, dirs, files in os.walk(basedir + line):
|
|
for file in files:
|
|
file_path = os.path.join(root, file)
|
|
zip.write(file_path)
|
|
else:
|
|
zip.write(basedir + line)
|
|
|
|
# if first of month, copy over
|
|
if now.day == 1:
|
|
shutil.copy(daily_dir + target_filename, monthly_dir)
|
|
|
|
# delete old backups
|
|
for filename in os.listdir(daily_dir):
|
|
date_object = datetime.strptime(filename[:10], '%Y-%m-%d')
|
|
delta = today - date_object
|
|
if delta.days > days_to_keep:
|
|
os.remove(daily_dir + filename)
|
|
|
|
for filename in os.listdir(monthly_dir):
|
|
date_object = datetime.strptime(filename[:10], '%Y-%m-%d')
|
|
num_months = (today.year - date_object.year) * 12 + (today.month - date_object.month)
|
|
if num_months > months_to_keep:
|
|
os.remove(monthly_dir + filename)
|
|
|
|
|