Skip to content

Instantly share code, notes, and snippets.

@jniltinho
Created January 21, 2015 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jniltinho/3a67b828ca283f1223ce to your computer and use it in GitHub Desktop.
Save jniltinho/3a67b828ca283f1223ce to your computer and use it in GitHub Desktop.
Backup VMs XenServer/XCP
#!/usr/bin/python
# -*- coding: utf-8 -*-
## Versao 0.3
### Colocar no Crontab
## Script para Backup do Citrix
## 15 03 * * * /usr/local/bin/backup_vms.py --backup --sendmail --clean=3
import os, sys, optparse, socket
import commands, time
#from smtplib import SMTP_SSL as SMTP #secure SMTP protocol (port 465, uses SSL)
from smtplib import SMTP #standard SMTP protocol (port 25,587, no SSL)
from email.MIMEText import MIMEText
#---------------------------------------------------------------------------
## esses campos podem ser alterados
verbose = False
message = ''
hostname = socket.gethostname()
backup_dir = '/backups/vms'
log_file = '/var/log/backup_vms.log'
l_hostname = hostname + '.seudominio.com.br'
SMTPserver = 'webmail.seudominio.com.br'
sender = 'xenserver@seudominio.com.br'
USERNAME = 'xenserver@seudominio.com.br'
PASSWORD = 'xen0111'
destination = ['suporte@seudominio.com.br']
des_ccc = ['suporte2@seudominio.com.br']
skip = ['d4b80e35-0dc7-bdfc-3806-d5b3cd746907']
#---------------------------------------------------------------------------
def get_backup_vms():
result = []
log("BACKUP FROM: %s" %(hostname) )
cmd = "xe vm-list is-control-domain=false"
output = commands.getoutput(cmd)
for vm in output.split("\n\n\n"):
lines = vm.split("\n")
UUID = lines[0].split(":")[1][1:]
NAME = lines[1].split(":")[1][1:]
if UUID in skip:
log('Skipping backup of: %s uuid: %s' %(NAME, UUID))
else:
uuid = lines[0].split(":")[1][1:]
name = lines[1].split(":")[1][1:]
result += [(uuid, name)]
return result
def backup_vm(name, uuid, filename, timestamp):
cmd = "xe vm-snapshot uuid=" + uuid + " new-name-label=" + name
snapshot_uuid = commands.getoutput(cmd)
log(snapshot_uuid)
cmd = "xe template-param-set is-a-template=false ha-always-run=false uuid=" + snapshot_uuid
cmd_result = commands.getoutput(cmd)
log(cmd_result)
filename = filename.replace(" ", "\ ")
filename = filename.replace("(", "\(")
filename = filename.replace(")", "\)")
cmd = "xe vm-export compress=true vm=" + snapshot_uuid + " filename=" + filename
cmd_result = commands.getoutput(cmd)
log(cmd_result)
cmd = "xe vm-uninstall uuid=" + snapshot_uuid + " force=true"
cmd_result = commands.getoutput(cmd)
log(cmd_result)
def clean_files(BackupDir, DaysToKeep):
now = time.time()
filelist = [ f for f in os.listdir(BackupDir) if f.endswith(".xva") ]
for f in filelist:
f = os.path.join(BackupDir, f)
if os.stat(f).st_mtime < now - (DaysToKeep * 86400):
if os.path.isfile(f):
os.remove(f)
log('APAGANDO O ARQUIVO: %s COM MAIS DE %s DIAS ...' %(f, DaysToKeep))
def exec_backup():
for (uuid, name) in get_backup_vms():
timestamp = time.strftime('%Y%m%d_%H%M')
filename = ("%s/%s-%s.xva") %(backup_dir, name, timestamp)
log("Backup name: %s filename: %s" %(name, filename))
backup_vm(name, uuid, filename, timestamp)
def log(mes):
global message
str = ("%s - %s\n") %(time.strftime('%b %d %H:%M:%S'), mes)
message += str
if verbose: str = str.rstrip("\n"); print str
def send_mail(receiver, Subject):
global message
subject = ("%s JOB: %s HOST: %s") %(Subject, sys.argv[0], hostname)
receiver = receiver
text_subtype = 'plain'
try:
msg = MIMEText(message, text_subtype)
msg['Subject']= subject
msg['From'] = sender
msg['To'] = ', '.join(receiver)
receiver = receiver + des_ccc
conn = SMTP(SMTPserver,587,l_hostname)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, receiver, msg.as_string())
finally:
conn.close()
except Exception, exc:
log( "mail failed; %s" % str(exc) ) # give a error message
def main():
global verbose, message
usage = "usage: %prog --backup [options]"
parser = optparse.OptionParser(usage)
parser.add_option("--clean", action="store", type="int", dest="CLEAN", default=False, help="Para limpar os arquivos X dias")
parser.add_option("--backup", action="store_true", dest="BACKUP", default=False, help="Para fazer Backup")
parser.add_option("--debug", action="store_true", dest="DEBUG", default=False, help="Para habilitar Debug")
parser.add_option("--sendmail", action="store_true", dest="SENDMAIL", default=False, help="Para enviar E-mail")
options, args = parser.parse_args()
if (options.DEBUG): verbose = True
if (options.BACKUP):
log("[***JOB DE BACKUP XENSERVER****]")
exec_backup()
if (options.CLEAN): clean_files(backup_dir, options.CLEAN)
if (options.SENDMAIL): send_mail(destination, "LOG BACKUP XENSERVER")
salve_log = open(log_file,"w"); salve_log.write(message); salve_log.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment