python备份数据库并发送邮件提醒

python备份数据库并发送邮件提醒


示例代码.

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import time
import sys
import datetime
import smtplib
import string
from stat import *

USER = 'root'
PASSWORD = '123456'
PORT = '3306'
# MYSQLDUMP = '/usr/bin/mysqldump' #自定义安装的,看自己安装的目录即可
MYSQLDUMP = 'docker exec -i  mysql mysqldump ' #这个是docker命令
DATABASES = ['test1','test2']
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  + ' -u' +  USER  + ' -p' + PASSWORD  + " " +  DB  + ' >'  +  Backupfile_name
        # break
        if os.system(Backup_command) == 0:
            TEXT = Backupfile_name + "数据库备份成功"
            HOST = "smtp.163.com"
            FROM = "to_darcy@163.com"
            PASS='1111' #smtp密码
            TO = ['todarcy@163.com']
            SUBJECT = Backupfile_name + "数据库备份成功"
            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 = Backupfile_name + "数据库备份Fail"
            HOST = "smtp.163.com"
            FROM = "to_darcy@163.com"
            PASS='11111'
            TO = ['todarcy@163.com']
            SUBJECT = Backupfile_name + "数据库备份情况"
            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 'Fail gzip' + Backupfile_name +  ' to ' + Gzipfile_name
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值