import os import time import sched import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication import datetime # 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数 # 第二个参数以某种人为的方式衡量时间 schedule = sched.scheduler(time.time, time.sleep) # 数据库 DB_USER = 'root' # 账户 db = 'xx' DB_USER_PASSWORD = 'password' # 密码 TODAY_BACKUP_PATH = 'xx' # 备份名称、或加上路径 NEW_FILE = '' # 组合后的文件名 # 邮箱 _user = "xxxxxx@163.com" # 发送者的邮箱 _pwd = "password" # 发送者的密码 _to = "xzxytx1zy@163.com" # 接收者的邮箱 def backupsDB(): d = datetime.datetime.now().strftime('%d') # 日是整数保存文件加上日期, 否则不加 if d in ['01', '10', '20', '30']: backupsDB_number(d + TODAY_BACKUP_PATH) else: backupsDB_number(TODAY_BACKUP_PATH) # 备份一次到今天 def backupsDB_number(new_file): """备份""" global NEW_FILE NEW_FILE = new_file cmdString = 'mysqldump -u%s -p%s %s > %s.sql' % (DB_USER, DB_USER_PASSWORD, db, new_file) os.system(cmdString) def sendMail(): # 如名字所示Multipart就是分多个部分 msg = MIMEMultipart() msg["Subject"] = "数据备份" msg["From"] = _user msg["To"] = _to # ---这是文字部分--- part = MIMEText("数据库备份") msg.attach(part) # ---这是附件部分--- # 类型附件 part = MIMEApplication(open('./%s.sql' % NEW_FILE, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename="%s.sql" % NEW_FILE) msg.attach(part) s = smtplib.SMTP("smtp.163.com", timeout=30) # 连接smtp邮件服务器,端口默认是25 s.login(_user, _pwd) # 登陆服务器 s.sendmail(_user, _to, msg.as_string()) # 发送邮件 s.close() def perform_command(cmd, inc): # 安排inc秒后再次运行自己,即周期运行 schedule.enter(inc, 0, perform_command, (cmd, inc)) os.system(cmd) backupsDB() try: sendMail() except: with open('record.txt', 'a')as f: f.write(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + ':发送邮件失败;\n') def timming_exe(cmd, inc=60): # enter用来安排某事件的发生时间,从现在起第n秒开始启动 schedule.enter(inc, 0, perform_command, (cmd, inc)) # 持续运行,直到计划时间队列变成空为止 schedule.run() if __name__ == '__main__': print("show time after 10 seconds:") # 86400 是一天的秒数 timming_exe("echo %time%", 56400) # 每间隔56400秒备份发送邮件 # 46400 基本上是半天
定时对mysql备份、并发送邮件
最新推荐文章于 2024-07-23 09:51:01 发布