码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-01-25 17:24:02      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:python mysql smtp

#!/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

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

标签:python mysql smtp

原文地址:http://yujianglei.blog.51cto.com/7215578/1738309

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!