mysql_backup.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #!/usr/bin/python
  2. import os
  3. import tarfile
  4. import smtplib
  5. from email.header import Header
  6. from email.mime.text import MIMEText
  7. from email.mime.multipart import MIMEMultipart
  8. from collections import namedtuple
  9. from datetime import datetime
  10. """
  11. MySQL dumper tool
  12. used for backup mysql automatically(which could be done by cron).
  13. Aims:
  14. 1. support multiple database
  15. 2. support dump to local basically and push to remote server/send an email
  16. """
  17. """ Config Section """
  18. db_t = namedtuple('db_t', ['host', 'port', 'db', 'username', 'password'])
  19. smtp_t = namedtuple('smtp_t', ['server', 'sender', 'username', 'password',
  20. 'to', 'title'])
  21. # mysql config
  22. mylist = [
  23. db_t('localhost', # host
  24. 3306, # port
  25. 'twongd', # db
  26. 'twongd', # username
  27. 'twongd'), # password
  28. ]
  29. # email config
  30. email = smtp_t('smtp.163.com', # smtp server
  31. 'yyk882002@163.com', # from
  32. 'yyk882002@163.com', # username
  33. 'initialize', # password
  34. 'wedtrav@foxmail.com', # to
  35. 'twongd backup') # title
  36. # local config
  37. saveto = '/tmp/'
  38. """ /Config Section """
  39. def dump():
  40. """
  41. return False or saved filename
  42. """
  43. files = []
  44. for my in mylist:
  45. filename = my.db + datetime.now().strftime('_%Y_%m_%d_%H_%M_%S.sql')
  46. dest = os.path.join(saveto, filename)
  47. cmd = 'mysqldump -h {} -u {} --password={} {} > {}'.format(
  48. my.host, my.username, my.password, my.db, dest
  49. )
  50. if os.system(cmd):
  51. break
  52. files.append(dest)
  53. return files
  54. def create_targz(source_files, dest_file):
  55. try:
  56. with tarfile.open(dest_file, 'w:gz') as tar:
  57. for file in source_files:
  58. tar.add(file)
  59. return True
  60. except Exception as e:
  61. print(e)
  62. return False
  63. def send_mail(sqlfile):
  64. """
  65. return bool
  66. """
  67. msg = MIMEMultipart()
  68. msg['From'] = email.sender
  69. msg['To'] = email.to
  70. msg['Subject'] = Header(email.title, 'utf-8')
  71. msg.attach(MIMEText('daily backup', 'plain', 'utf-8'))
  72. att = MIMEText(str(open(sqlfile, 'rb').read()), 'base64', 'utf-8')
  73. att['Content-Type'] = 'application/octet-stream'
  74. name = os.path.basename(sqlfile)
  75. att['Content-Disposition'] = 'attachment; filename={}'.format(name)
  76. msg.attach(att)
  77. smtp_obj = smtplib.SMTP_SSL()
  78. smtp_obj.connect(email.server)
  79. smtp_obj.login(email.username, email.password)
  80. smtp_obj.sendmail(email.sender, email.to, msg.as_string())
  81. smtp_obj.quit()
  82. def main():
  83. # check config
  84. if not mylist:
  85. print('no any mysql configurations')
  86. return
  87. # dump to sql files
  88. sqlfiles = dump()
  89. if not sqlfiles:
  90. print('ERROR: dump failed')
  91. return
  92. # compress all sql files
  93. tmp_targz = datetime.now().strftime('/tmp/%H_%m_%s_%H:%M_%S.tar.gz')
  94. if not create_targz(sqlfiles, tmp_targz):
  95. print('compress .sql failed')
  96. return
  97. # send email
  98. send_mail(tmp_targz)
  99. # remove sql files (keep .tar.gz on dist)
  100. _ = [os.remove(sql) for sql in sqlfiles]
  101. if __name__ == '__main__':
  102. main()