python备份数据库并发送邮件提醒
示例代码
.
import os
import time
import sys
import datetime
import smtplib
import string
from stat import *
USER = 'root'
PASSWORD = '123456'
PORT = '3306'
MYSQLDUMP = 'docker exec -i mysql mysqldump '
DATABASES = ['test1','test2']
TO_BACKUP_DIR="/tmp/data_backup/"
for DB in DATABASES:
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
if os.system(Backup_command) == 0:
TEXT = Backupfile_name + "数据库备份成功"
HOST = "smtp.163.com"
FROM = "to_darcy@163.com"
PASS='1111'
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