记录下自己学习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' username = 'to_darcy@163.com' password = '123456' msg = MIMEMultipart() 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) 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 = ['yao','icaesee'] 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()