Python實現定時備份mysql資料庫並把備份資料庫郵件發送,pythonmysql

來源:互聯網
上載者:User

Python實現定時備份mysql資料庫並把備份資料庫郵件發送,pythonmysql

一、先來看備份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"] = "商城Database Backup"   msg["From"] = _user   msg["To"] = _to   # ---這是文字部分---   part = MIMEText("商城Database Backup")   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資料庫並把備份資料庫郵件發送,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.