#!/usr/bin/env python import os import time import MySQLdb import sys SENDMAIL = "/usr/sbin/sendmail" # sendmail location username = "backupuser" password = "backuppass" hostname = "localhost" filestamp = time.strftime('%d-%m-%Y') # Get a list of databases on the mysql server database_list_command="mysql -u %s -p%s -h %s --silent -N -e 'show databases'" % (username, password, hostname) for database in os.popen(database_list_command).readlines(): database = database.strip() # Check if the auto backup module is enabled and get the notification data notify_db = MySQLdb.connect( user=username,passwd=password,db=database) c = notify_db.cursor() try: c.execute("SELECT `notify_email`,`enabled` FROM `backup_config` WHERE 1 LIMIT 1") result = c.fetchone() notify_to = result[0] enabled = result[1] except MySQLdb.Error, e: continue if enabled == 1: filename = "/backups/mysql/%s-%s.sql" % (database, filestamp) os.popen("mysqldump -u %s -p%s -h %s -e --opt -c %s | gzip -c > %s.gz" % (username, password, hostname, database, filename)) FROM = "backup@mydomainhere.com.au" if notify_to == "": notify_to = "backup@mydomainhere.com.au" TO = [notify_to] # using a list to make it easier to support multiple addresses SUBJECT = "Backup Complete Notification" TEXT = "The latest database backup has been complete." # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail p = os.popen("%s -t -i" % SENDMAIL, "w") p.write(message) status = p.close() if status: print "Sendmail exit status", status