python备份mysql数据库并发送邮件

时间:2022-04-28 18:08:41
#!/usr/bin/env python
#coding:utf-8
#Write by JIANGLEI.YU
#Update On  2016-01-24 20:26
import os
import time
import sys
import datetime
import smtplib
import string
from stat import *
#Define DB  Informations
HOST = '192.168.0.135'
USER = 'root'
PASSWORD = '123456'
PORT = '3306'
MYSQLDUMP = '/usr/bin/mysqldump'
GZIP = '/usr/bin/gzip'
DATABASES = ['virtualTest']
TO_BACKUP_DIR="/tmp/data_backup/"
for  DB in  DATABASES:
    #backup file name
    Backupfile_name = TO_BACKUP_DIR + DB +  '-' + time.strftime('%Y-%m-%d') + '.sql'
    Gzipfile_name = Backupfile_name + '.gz'
    if os.path.isfile(Gzipfile_name):
        print Gzipfile_name + " is already backup"
    else:
        Backup_command = MYSQLDUMP  + ' -h' + HOST + ' -u' +  USER  + ' -p' + PASSWORD  + ' --single-transaction ' +   DB  + ' >'  +  Backupfile_name
        if os.system(Backup_command) == 0:
            TEXT = "virtual数据库备份成功"
            HOST = "smtp.163.com"
            FROM = "15614119390@163.com"
            PASS='123456'
            TO = ['15011254881@139.com','yujianglei@singulax.com']
            SUBJECT = "virtual数据库备份情况"
            BODY=string.join((
                    "From: %s" %FROM,
                    "To: %s" %TO,
                    "Subject: %s" %SUBJECT,
                    "",
                    TEXT
                    ),"\r\n")
            Server=smtplib.SMTP()
            Server.connect(HOST,25)
            Server.login(FROM,PASS)
            for to_user in TO:
                Server.sendmail(FROM,TO,BODY)
            Server.quit()
        else:
            TEXT = "virtual数据库备份成功"
            HOST = "smtp.163.com"
            FROM = "15614119390@163.com"
            PASS='123456'
            TO = ['15011254881@139.com','yujianglei@singulax.com']
            SUBJECT = "virtual数据库备份情况"
            BODY=string.join((
                    "From: %s" %FROM,
                    "To: %s" %TO,
                    "Subject: %s" %SUBJECT,
                    "",
                    TEXT
                    ),"\r\n")
            Server=smtplib.SMTP()
            Server.connect(HOST,25)
            Server.login(FROM,PASS)
            for to_user in TO:
                    Server.sendmail(FROM,TO,BODY)
            Server.quit()
        GZIP_command = GZIP + ' ' +  Backupfile_name
        if os.system(GZIP_command) == 0:
                print 'Successful gzip' + Backupfile_name +  ' to ' + Gzipfile_name
        else:
                print 'Successful gzip' + Backupfile_name +  ' to ' + Gzipfile_name

本文出自 “不求最好,只求更好” 博客,请务必保留此出处http://yujianglei.blog.51cto.com/7215578/1738309