Python实现定时备份mysql数据库并把备份数据库邮件发送

yipeiwu_com6年前Python基础

一、先来看备份mysql数据库的命令

mysqldump -u root --password=root --database abcDataBase > c:/abc_backup.sql 

二、写Python程序

       BackupsDB.py

#!/usr/bin/python 
# -*- coding: UTF-8 -*- 
 ''''' 
zhouzhongqing 

备份数据库  

''' 
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 
# 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数 
# 第二个参数以某种人为的方式衡量时间 
schedule = sched.scheduler(time.time, time.sleep); 
def backupsDB(): 
        # 如果是linux改下路径就可以了 
  cmdString = 'D:/php/phpStudy/MySQL/bin/mysqldump -u root --password=root --database abcDataBase > c:/abc_backup.sql'; 
  os.system(cmdString); 
def sendMail(): 
  _user = "mall@xxxx.com"#发送者的邮箱 
  _pwd = "xxxx"#发送者的密码 
  _to = "1030907690@qq.com"#接收者的邮箱 
  # 如名字所示Multipart就是分多个部分 
  msg = MIMEMultipart() 
  msg["Subject"] = "商城数据库备份" 
  msg["From"] = _user 
  msg["To"] = _to 
  # ---这是文字部分--- 
  part = MIMEText("商城数据库备份") 
  msg.attach(part) 
  # ---这是附件部分--- 
  # 类型附件 
  part = MIMEApplication(open('c:/abc_backup.sql', 'rb').read()) 
  part.add_header('Content-Disposition', 'attachment', filename="abc_backup.sql") 
  msg.attach(part) 
  s = smtplib.SMTP("smtp.exmail.qq.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(); 
  sendMail(); 
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:"); 
  timming_exe("echo %time%", 56400);#每间隔56400秒备份发送邮件 
  #46400 基本上是半天 

然后命令

py BackupsDB.py 

运行程序就可以了。

总结

以上所述是小编给大家介绍的Python实现定时备份mysql数据库并把备份数据库邮件发送,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python字符串拼接六种方法介绍

Python字符串拼接的6种方法: 1.加号 第一种,有编程经验的人,估计都知道很多语言里面是用加号连接两个字符串,Python里面也是如此直接用“+”来连接两个字符串; print...

python的slice notation的特殊用法详解

python的slice notation的特殊用法详解

如下所示: python的slice notation的特殊用法。 a = [0,1,2,3,4,5,6,7,8,9] b = a[i:j] 表示复制a[i]到a[j-1],以生成新的...

对Python3中的print函数以及与python2的对比分析

对Python3中的print函数以及与python2的对比分析

本文首先介绍在python3中print函数的应用,然后对比在pyhton2中的应用。(本文作者所用版本为3.6.0) 首先我们通过help(print)命令来查看print函数的相关信...

Python 虚拟空间的使用代码详解

Python 虚拟空间的使用代码详解

具体代码如下所示: # 在项目根目录创建 python3 -m venv 虚拟空间名称 ## 如 python3 -m venv myvenv # 对于 macOS ## 在项目根...

django加载本地html的方法

django加载本地html的方法

django加载本地html from django.shortcuts import render from django.http import HttpResponse fro...