python备份数据库并发送邮件附件(上篇文章升级版)
上一篇是关于备份后进行邮件提醒的功能 这个是进行备份后,并发送邮件附件进行保存的功能。 相对来说比较简陋,可以自行修改,简略步骤,美化过程等。
示例代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import time
import smtplib
import string
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendMail(datas):
# 定义相关数据,请更换自己的真实数据
smtpserver = 'smtp.163.com'
sender = 'to_darcy@163.com'
# receiver可设置多个,使用“,”分隔
receiver = 'todarcy@163.com,aaa@163.com'
username = 'to_darcy@163.com'
password = '123456'
msg = MIMEMultipart()
if len(datas) > 0:
for i in datas:
att = MIMEText(open(i, "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
i = i.replace("/tmp/data_backup/", "")
att["Content-Disposition"] = 'attachment; filename= %s ' %i
msg.attach(att)
else:
att = MIMEText(open(datas, "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
datas = datas.replace("/tmp/data_backup/","")
att["Content-Disposition"] = 'attachment; filename= %s ' %datas
msg.attach(att)
receivers = receiver
toclause = receivers.split(',')
msg['To'] = ",".join(toclause)
# 添加主题,不然提示554 DT:SPM错误
msg['SUBJECT'] = "数据库备份成功"
# 登陆并发送邮件
smtp = smtplib.SMTP()
try:
# # 打开调试模式
# smtp.set_debuglevel(1)
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receivers, msg.as_string())
except:
print("邮件发送失败!!")
else:
print("邮件发送成功")
finally:
smtp.quit()
def mysqldump():
USER = 'root'
PASSWORD = '123456'
MYSQLDUMP = 'docker exec -i mysql mysqldump '
DATABASES = ['test1','test2']
TO_BACKUP_DIR="/tmp/data_backup/"
lists = [];
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
print Backup_command
# break
if os.system(Backup_command) == 0:
lists.append(Gzipfile_name)
else:
print "Fail"
# 打包压缩成.gz
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
if len(lists) > 0:
sendMail(lists)
mysqldump()