MySQL backup using Python


SUBMITTED BY: Guest

DATE: Jan. 20, 2013, 4:16 a.m.

FORMAT: Text only

SIZE: 2.0 kB

HITS: 1551

  1. #!/usr/bin/env python
  2. import os
  3. import time
  4. import MySQLdb
  5. import sys
  6. SENDMAIL = "/usr/sbin/sendmail" # sendmail location
  7. username = "backupuser"
  8. password = "backuppass"
  9. hostname = "localhost"
  10. filestamp = time.strftime('%d-%m-%Y')
  11. # Get a list of databases on the mysql server
  12. database_list_command="mysql -u %s -p%s -h %s --silent -N -e 'show databases'" % (username, password, hostname)
  13. for database in os.popen(database_list_command).readlines():
  14. database = database.strip()
  15. # Check if the auto backup module is enabled and get the notification data
  16. notify_db = MySQLdb.connect( user=username,passwd=password,db=database)
  17. c = notify_db.cursor()
  18. try:
  19. c.execute("SELECT `notify_email`,`enabled` FROM `backup_config` WHERE 1 LIMIT 1")
  20. result = c.fetchone()
  21. notify_to = result[0]
  22. enabled = result[1]
  23. except MySQLdb.Error, e:
  24. continue
  25. if enabled == 1:
  26. filename = "/backups/mysql/%s-%s.sql" % (database, filestamp)
  27. os.popen("mysqldump -u %s -p%s -h %s -e --opt -c %s | gzip -c > %s.gz" % (username, password, hostname, database, filename))
  28. FROM = "backup@mydomainhere.com.au"
  29. if notify_to == "":
  30. notify_to = "backup@mydomainhere.com.au"
  31. TO = [notify_to] # using a list to make it easier to support multiple addresses
  32. SUBJECT = "Backup Complete Notification"
  33. TEXT = "The latest database backup has been complete."
  34. # Prepare actual message
  35. message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
  36. # Send the mail
  37. p = os.popen("%s -t -i" % SENDMAIL, "w")
  38. p.write(message)
  39. status = p.close()
  40. if status:
  41. print "Sendmail exit status", status

comments powered by Disqus