Python實現定時備份mysql資料庫並把備份資料庫郵件傳送
阿新 • • 發佈:2020-01-09
一、先來看備份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 = "[email protected]"#傳送者的郵箱 _pwd = "xxxx"#傳送者的密碼 _to = "[email protected]"#接收者的郵箱 # 如名字所示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,perform_command,(cmd,inc)); os.system(cmd); backupsDB(); sendMail(); def timming_exe(cmd,inc=60): # enter用來安排某事件的發生時間,從現在起第n秒開始啟動 schedule.enter(inc,inc)) # 持續執行,直到計劃時間佇列變成空為止 schedule.run() if __name__ == '__main__': print("show time after 10 seconds:"); timming_exe("echo %time%",56400);#每間隔56400秒備份傳送郵件 #46400 基本上是半天
然後命令
py BackupsDB.py
執行程式就可以了。
總結
以上所述是小編給大家介紹的Python實現定時備份mysql資料庫並把備份資料庫郵件傳送,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!