Spiga

Script para hacer Backups

April 06, 09 by admin

Me he hecho un pequeño script en Python que llamo todos los dias en en el cron para que me haga un backup.
Utiliza scp y lo tengo configurado con certificado de la máquina ‘backup’ hacía la que va a copiar.

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
#!/usr/bin/env python
import os, time, smtplib, sys, subprocess, StringIO
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 
email = "email@dominio" #email al que vas a enviar
email_from = "email@dominio" #Desde el que vas a enviar
path = "/path/donde/guardar/el/backup"
path_l = path + "files/"
path_h = "/path/de/la/maquina/remota/a/copiar"
host = "ip_o_dominio"
user = "cacaue"
 
def writelog(content):
log=open(path+'log.txt', 'a')
log.write(time.strftime("%d %m %Y %H:%M")+"  "+content+"\r\n")
log.close()
 
def sendemail(content, asunto):
msg = MIMEMultipart()
msg['To'] = email
msg['Cc'] = ""
msg['From'] = email_from
msg['Subject'] = asunto
text = MIMEText(content)
text.add_header("Content-Disposition", "inline")
msg.attach(text)
 
try:
server=smtplib.SMTP("localhost")
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
writelog("Email enviado a "+msg['To']+" con el contenido: "+content)
except:
writelog("Error al enviar email")
 
if __name__ == "__main__":
path_backup = path_l+time.strftime("%d%m%y")
try:
os.mkdir(path_backup)
except:
writelog("Ya existe --> "+path_backup)
 
cmd = "scp -r "+user+"@"+host+":"+path_h+" "+path_backup
try:
f=open(path+"temp.txt", "w")
retcode = subprocess.call(cmd, shell=True, stdin=f, stderr=f)
f.close()
if retcode < 0:
writelog("Child was terminated by signal")
else:
f=open(path+"temp.txt", "r")
salida = f.read()
f.close()
if os.path.getsize(path+"temp.txt")>0:
writelog("Error en "+host)
else:
sendemail(salida, "Backup "+time.strftime("%d/%m/%y")+" realizado con exito")
writelog("Realizado con exito")
 
except OSError, e:
writelog("Execution failed")
Add your comment

One response for this post

  1. Felipe Says:

    Hola que bueno ese scrips . no si sepas como hacerlo con rsycn..

Leave a Reply