Python實現定時備份mysql數據庫並把備份數據庫郵件發送

1、先來看備份mysql數據庫的命令php

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

2、寫Python程序python

       BackupsDB.pymysql

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

備份數據庫  linux

''' 
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 基本上是半天

而後命令sql

py BackupsDB.py

運行程序就能夠了。數據庫

相關文章
相關標籤/搜索