Backup and restore files from specific folders. Maybe someone could make it keep track of where it was backed up from and restore back to previous location…
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 63 64 65 66 67 68 69 |
#!/usr/bin/python import sys import optparse import os import time import glob import shutil BACKUP_DIR='/home/user/backups' RESTORE_DIR='/home/user/restore' def get_args(): p = optparse.OptionParser() p.add_option('--backup', dest='backup', default=None, help='Backup given file (include filepath).') p.add_option('--restore', dest='restore', default=None, help='Restore the latest version of a file, only requires file name.') (opts, args) = p.parse_args() if not opts.backup and not opts.restore: p.error("Incorrect arguments") sys.exit(1) return opts def add_file(file_path, name): copy_location = BACKUP_DIR + "/" + name shutil.copyfile(file_path, copy_location) print "Backed up file to " + BACKUP_DIR + "/" + backup_name def find_latest_file(file): file_l = glob.glob(BACKUP_DIR + "/" + file + "_*") file_l.sort() file_l.reverse() # descending if not len(file_l[0]): raise Exception("Could not find file in backups.") return os.path.basename(file_l[0]) def original_name_from_backup(file): split_f = file.split("_") if len(split_f) > 1: return ("_").join(split_f[0:-1]) else: return split_f[0] def name_file(file): return file + "_" + time.strftime("%Y%m%d-%H%M%S") if __name__ == "__main__": opts = get_args() if not os.path.isdir(BACKUP_DIR): print "Backup directory", BACKUP_DIR, " does not exist." sys.exit(1) if not os.path.isdir(RESTORE_DIR): print "Restore directory", RESTORE_DIR, " does not exist." sys.exit(1) if opts.backup: file_path = opts.backup if not os.path.isfile(file_path): raise Exception("Invalid file.") f = os.path.basename(file_path) backup_name = name_file(f) add_file(file_path, backup_name) if opts.restore: f = find_latest_file(opts.restore) f_orig_name = original_name_from_backup(f) shutil.copyfile(BACKUP_DIR + "/" + f, RESTORE_DIR + "/" + f_orig_name) print "Restored file " + f_orig_name + " to " + RESTORE_DIR |
Questions? Comments?