Skip to content

Instantly share code, notes, and snippets.

@bienvenidosaez
Created March 21, 2015 12:34
Show Gist options
  • Save bienvenidosaez/f383c4214e008af7f9ad to your computer and use it in GitHub Desktop.
Save bienvenidosaez/f383c4214e008af7f9ad to your computer and use it in GitHub Desktop.
Python Folder Backup in MEGA
#!/usr/bin/python
# -*- encoding: utf-8 -*-
######################################################################################################
## ##
## SCRIPT EN PYTHON PARA EL RESPALDO DE DIRECTORIOS Y SUBIDA A MEGA ##
## ##
## Almacenará tres tipos de copia: ##
## - Diarias: el sistema realizará una copia diaria por carpeta eliminará aquellas ##
## que tengan más de N_DAYS_AGO_DIARY_BACKUP días de antiguedad ##
## - Semanales: el sistema realizará una copia semanal cada viernes de cada carpeta y ##
## eliminará aquellas que tengan más de N_WEEKS_AGO_BACKUP semanas de antiguedad ##
## - Mensuales: el sistema realizará una copia mensual los días 1 de cada mes y eliminará ##
## aquellas que tengan más de N_MONTHS_AGO_BACKUP meses de antiguedad ##
## ##
## ##
## * para poder subir los ficheros a mega es necesario instalar el siguiente requerimiento ##
## https://github.com/richardasaurus/mega.py ##
## ##
## sudo pip install mega.py ##
## ##
## ##
## @bienvenidosaez ##
## ##
######################################################################################################
from time import gmtime, strftime
import subprocess
import os
import glob
import time
from mega import Mega # sudo pip install mega.py
FOLDER_LIST = (
{
'name' : 'NameFileFolder',
'path' : '/path/to/folder'
},
)
BACKUP_DIR = '/var/backups/' # directorio para guardar las copias
MONTH_DAY = '1' # día del mes para la copia mensual
WEEK_DAY = '7' # día de la semana para las copias semanal [1(Monday), 7]
N_DAYS_AGO = 30 # nº de copias diarias a almacenar
N_WEEKS_AGO = 4 # nº de copias semanas que se almecenarán
N_MONTHS_AGO = 12 # nº de copias mensuales que se almacenarán
TARER = """ tar -czf %s -P %s """
# MEGA
MEGA = False # True = sube los archivos generados a la cuenta MEGA indicada
MEGA_EMAIL = 'mega@email.com' # Email de MEGA
MEGA_PASSWORD = 'megapass' # Password de MEGA
MEGA_FOLDER = 'megafolder' # Directorio donde subir los backup en MEGA
def log(string):
print time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime()) + ': ' + str(string)
def diary_backup(folder):
global BACKUP_DIR
global MEGA
global MEGA_FOLDER
global TARER
print("===== START diary backup for %s =====" % folder['name'])
# Iteramos sobre las copias diarias, este apartado se ejecutará en cada ejecución del fichero
glob_list = glob.glob(BACKUP_DIR + folder['name'] + '_diary_backup*' + '.tar.gz')
for file in glob_list:
file_info = os.stat(file)
if file_info.st_ctime < x_days_ago:
log("Delete diary backup: %s" % file)
os.unlink(file)
else:
log("Keep diary backup: %s" % file)
thetime = str(strftime("%Y-%m-%d"))
file_name = folder['name'] + '_diary_backup_' + thetime + ".tar.gz"
command = TARER % (BACKUP_DIR + file_name, folder['path'])
log(command)
subprocess.call(command, shell=True)
if MEGA:
mega_upload_file(BACKUP_DIR + file_name, MEGA_FOLDER)
print("===== END diary backup for %s =====\n" % folder['name'])
def week_backup(database):
global BACKUP_DIR
global DUMPER
global MEGA
global MEGA_FOLDER
print("\n===== START week backup for %s =====" % folder['name'])
glob_list = glob.glob(BACKUP_DIR + folder['name'] + '_week_backup*' + '.tar.gz')
for file in glob_list:
file_info = os.stat(file)
if file_info.st_ctime < x_montsh_ago:
log("Delete week backup: %s" % file)
os.unlink(file)
else:
log("Keep week backup: %s" % file)
thetime = str(strftime("%Y-%m-week-%U"))
file_name = folder['name'] + '_week_backup_' + thetime + ".tar.gz"
command = TARER % (BACKUP_DIR + file_name, folder['path'])
log(command)
subprocess.call(command, shell=True)
if MEGA:
mega_upload_file(BACKUP_DIR + file_name, MEGA_FOLDER)
print("===== END week backup for %s =====\n" % folder['name'])
def month_backup(database):
global BACKUP_DIR
global DUMPER
global MEGA
global MEGA_FOLDER
print("===== START month backup for %s =====" % folder['name'])
# Iteramos sobre las copias mensuales
glob_list = glob.glob(BACKUP_DIR + folder['name'] + '_month_backup*' + '.tar.gz')
for file in glob_list:
file_info = os.stat(file)
if file_info.st_ctime < x_montsh_ago:
log("Delete month backup: %s" % file)
os.unlink(file)
else:
log("Keep month backup: %s" % file)
thetime = str(strftime("%Y-%m"))
file_name = folder['name'] + '_month_backup_' + thetime + ".tar.gz"
command = TARER % (BACKUP_DIR + file_name, folder['path'])
log(command)
subprocess.call(command, shell=True)
if MEGA:
mega_upload_file(BACKUP_DIR + file_name, MEGA_FOLDER)
print("===== END month backup for %s =====\n" % folder['name'])
def mega_connect():
global MEGA_EMAIL
global MEGA_PASSWORD
mega = Mega()
m = mega.login(MEGA_EMAIL, MEGA_PASSWORD)
return m
def mega_upload_file(file_to_upload, destination_path):
m = mega_connect()
file_info = os.stat(file_to_upload)
total_space = m.get_storage_space()['total']
total_used = m.get_storage_space()['used']
total_free = total_space - total_used
if total_free > file_info.st_size:
folder = m.find(destination_path)
return m.upload(file_to_upload, folder[0])
else:
return False
# Si el directorio no existe lo creamos
if not os.path.isdir(BACKUP_DIR):
os.makedirs(BACKUP_DIR, 0770)
x_days_ago = time.time() - ( 60 * 60 * 24 * N_DAYS_AGO )
x_weeks_ago = time.time() - ( 60 * 60 * 24 * N_WEEKS_AGO * 7)
x_montsh_ago = time.time() - ( 60 * 60 * 24 * N_MONTHS_AGO * 30)
# Iteramos sobre las bases de datos de las listas
for folder in FOLDER_LIST:
#La copia diaria la ejecutamos siempre
diary_backup(folder)
# Si estamos en el día del mes indicado en la variable MOTH_DAY hay que ejecutar la parte mensual del backup
if MONTH_DAY == time.strftime('%d', time.gmtime()):
month_backup(folder)
# Si estamos en el día de la semanaindicado en la variable WEEK_DAY hay que ejecutar la parte semanal del backup
if WEEK_DAY == time.strftime('%u', time.gmtime()):
week_backup(folder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment