Advertisement
Bl4ckP1r4t3

backupsql.py

Apr 14th, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import os, time, subprocess, smtplib
  4. from ConfigParser import ConfigParser
  5.  
  6. config = ConfigParser()
  7. # em Debian, /etc/mysql/debian.cnf contem 'root' login and password.
  8. config.read("/etc/mysql/debian.cnf")
  9. username = config.get('client', 'user')
  10. password = config.get('client', 'password')
  11. hostname = config.get('client', 'localhost')
  12. date = time.strftime('%Y-%m-%d-%H:%M')
  13. # diretorio de armazenamento dos backups
  14. dest = ""
  15.  
  16. def clear(directory):
  17. number_of_files = len([item for item in os.listdir(directory) if os.path.isfile(os.path.join(directory, item))])
  18. if number_of_files > 1:
  19. print "% s - Foram encontrados %s arquivos de backup no diretório %s" % (date, number_of_files, directory)
  20. purge_dir(directory)
  21. else:
  22. print "%s - Foram encontrados %s arquivos de backup nenhum será removido %s" % (date, number_of_files, directory)
  23.  
  24. def checkfile(filename):
  25. filestats = os.stat(filename) # pega informaçoes do arquivo
  26. if time.time() - filestats.st_mtime > 86400*7: # checa se o arquivo tem mais de 7 dias e remove caso positivo
  27. print "Removendo: %s" % (filename)
  28. os.remove(filename)
  29.  
  30. def purge_dir(path):
  31. dirList = os.listdir(path) # Lista o diretório
  32. for filename in dirList:
  33. checkfile(os.path.join(path, filename)) # executa funcao checkfile.
  34.  
  35.  
  36. def backup():
  37. database_list_command="mysql -u %s -p%s -h %s --silent -N -e 'show databases'" % (username, password, hostname) #lista databases
  38. for database in os.popen(database_list_command).readlines():
  39. database = database.strip()
  40. if database == 'information_schema':
  41. continue
  42. if database == 'performance_schema':
  43. continue
  44. if database == 'dvwa':
  45. continue
  46. print "%s - Criando Backup database: %s" % (date, database)
  47. target_dir = "%s/%s" % (dest, database)
  48. if not os.path.exists(target_dir):
  49. print "%s - Criando novo diretório: %s" % (date, target_dir)
  50. os.makedirs(target_dir)
  51. filename = "%s/%s-%s.sql" % (target_dir, database, date)
  52. os.popen("mysqldump --max_allowed_packet=128M --single-transaction -u %s -p%s -h%s %s | bzip2 -c > %s.bz2" % (username, password, hostname, database, filename))
  53. clear(target_dir)
  54.  
  55. backup()
  56.  
  57. smtp = smtplib.SMTP('', 587)
  58. smtp.starttls()
  59.  
  60. smtp.login('', '')
  61.  
  62. de = ''
  63. para = ['']
  64. msg = """From: %s
  65. To: %s
  66. Subject: test
  67.  
  68. email test ,""" % (de, ', '.join(para))
  69.  
  70. smtp.sendmail(de, para, msg)
  71.  
  72. smtp.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement