Create backup with python 3 multiple-archives
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import os
import datetime
import subprocess
import shutil
from pathlib import Path
home = str(Path.home())
now = datetime.datetime.now()
year = now.year
day = now.day
month = now.month
date_string = "{}_{}_{}".format(year, day, month)
#dest = '/media/disk1/backups/'
'''
dest var used to move created archives to another location
example : dest = '/media/disk/'
'''
dest = None
'''
folders is a list of folder paths to backup
for example
folders = [
'/var/www/',
'.ssh'
]
'''
folders = [
]
for folder in folders:
archived_name = None
exists = os.path.exists(folder)
if exists:
folder_path = folder
archived_name = "backup{}{}.tar.gz".format(
folder.replace('/', '_').replace('.',''), date_string)
if archived_name:
if not os.path.exists(archived_name):
print('create archive for folder :', archived_name)
out = subprocess.Popen(
['tar', '--exclude', '{}/env'.format(folder),
'{}/virtualenv'.format(folder),
'{}/bower_components'.format(
folder), '-zcvf', archived_name, folder],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
archive_exists = os.path.exists("{}/{}".format(home, archived_name))
if archive_exists:
print('archive {} created '.format(archived_name))
if dest:
filename = "{}/{}".format(home, archived_name)
shutil.move(os.path.join(
home, archived_name), os.path.join(dest, archived_name))
|