Last active
October 20, 2016 20:33
-
-
Save tonybolanyo/a4d24cd9f8ae58a91823af54a470ddbd to your computer and use it in GitHub Desktop.
Scripts para backup de servidor web en hosting compartido
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import paramiko | |
import socket | |
import sys | |
import traceback | |
paramiko.util.log_to_file('backup.log') | |
server = 'url.example.com' | |
username = 'username' | |
password = 'password' | |
script_dir = '/home/' | |
www_dir = '/www/' | |
logs_dir = '/logs/' | |
# Abre una sesión SSH y ejecuta el script de python en el servidor | |
# que crea el archivo ZIP de toda la web | |
try: | |
client = paramiko.SSHClient() | |
client.load_system_host_keys() | |
# client.set_missing_host_key_policy(paramiko.WarningPolicy()) | |
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
print('*** Connectando cliente SSH...') | |
client.connect(server, username=username, password=password) | |
print('*** Creando archivo ZIP con toda la web...') | |
stdin, stdout, stderr = client.exec_command('cd scripts; python make_www_zip.py -i /www') | |
stdin.close() | |
for line in iter(lambda: stdout.readline(2048), ""): print(line, end="") | |
print('*** Ejecución del script remoto terminada ***') | |
client.close() | |
print('*** Cerrado cliente SSH ***') | |
except Exception as e: | |
print('*** Excepción: %s: %s' % (e.__class__, e)) | |
traceback.print_exc() | |
try: | |
client.close() | |
except: | |
pass | |
sys.exit(1) | |
try: | |
t = paramiko.Transport(server) | |
print('*** Conectando sesión SFTP...') | |
t.connect(username=username, password=password) | |
sftp = paramiko.SFTPClient.from_transport(t) | |
# sftp.chdir('../httpd.private/scripts') | |
sftp.chdir(script_dir) | |
dirlist = sftp.listdir('.') | |
print('*** Buscando archivos ZIP sin descargar...') | |
for file in dirlist: | |
if file.endswith('.zip'): | |
print('*** Descargando archivo:', file) | |
sftp.get(file,file) | |
sftp.remove(file) | |
print('*** Archivo descargado y eliminado del servidor ***') | |
sftp.chdir(logs_dir) | |
dirlist = sftp.listdir('.') | |
# mantenemos solamente los logs del mes actual y del anterior | |
# es decir, máximo 60 días | |
this_month = datetime.date.today().strftime('%Y-%m') | |
last_month = (datetime.date.today() - datetime.timedelta(days=35)).strftime('%Y-%m') | |
print('*** Eliminando logs obsoletos de PyroCMS') | |
for file in dirlist: | |
if ( | |
file.startswith('log-'+this_month) | |
or file.startswith('log-'+last_month) | |
or file in ('index.html', '.htaccess')): | |
print("ignorando: " + file) | |
continue | |
print("eliminado: " + file) | |
sftp.remove(file) | |
t.close() | |
print('*** Conexión cerrada. Fin de la operación') | |
except Exception as e: | |
print('*** Excepción: ' + str(e.__class__) + ': ' + str(e)) | |
traceback.print_exc() | |
try: | |
t.close() | |
except: | |
àss | |
sys.exit(1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
call .\Env\Scripts\activate | |
python backup.py > log.txt | |
deactivate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Crea un archivo ZIP con todos los archivos de una ruta | |
a modo de copia de seguridad. | |
No utiliza exclusiones ni patrones. | |
Para Python 3.5.2 | |
Tony G. Bolanyo - Octubre 2016 | |
""" | |
from datetime import datetime | |
from getopt import getopt, GetoptError | |
import os | |
import sys | |
from zipfile import ZipFile, ZIP_DEFLATED | |
def create_zip(filename='zipfile.zip', path='.'): | |
""" | |
Crea el archivo zip y recorre recursivamente todos | |
los directorios agregando los aarchivos al archivo zip | |
""" | |
zip = ZipFile(filename, 'w', ZIP_DEFLATED) | |
print("") | |
# agregar archivos | |
for root, dirs, files in os.walk(path): | |
for file in files: | |
if file == filename: | |
continue | |
file_path = os.path.join(root, file) | |
print("... {}".format(file_path)) | |
zip.write(file_path) | |
zip.close() | |
print("") | |
def main(argv): | |
print("") | |
print("------------------------------") | |
print(" Creando ZIP para backup") | |
print("------------------------------") | |
print("") | |
date_format = '%Y%m%d%H%M%S' | |
path = '.' | |
filename = datetime.now().strftime(date_format) + '.zip' | |
try: | |
opts, args = getopt(argv, "hi:o:", ["input-path=", "output-file="]) | |
except GetoptError: | |
print("Forma de uso:") | |
print("\tpython make_zip.py -i <input-path> -o <output-file>") | |
print("") | |
print("Para ver la ayuda:") | |
print("\tpython make_zip.py -h") | |
print("") | |
sys.exit(2) | |
for opt, args in opts: | |
if opt == '-h': | |
print_help() | |
sys.exit() | |
elif opt in ('-i', '--input-path'): | |
path = args | |
print("\tRuta origen: {}".format(path)) | |
elif opt in ('-o', '--output-file'): | |
filename = args | |
print("\tArchivo de salida: {}".format(filename)) | |
create_zip(filename=filename, path=path) | |
print("") | |
print("Creado archivo {} a partir de la ruta {}".format(filename, path)) | |
def print_help(): | |
""" | |
Imprime ayuda para usar el script | |
""" | |
print("") | |
print("Forma de uso:") | |
print("") | |
print("\tpython make_zip.py -i <input-path> -o <output-file>") | |
print("") | |
print("Para ver la ayuda:") | |
print("") | |
print("\tpython make_zip.py -h") | |
print("") | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment