Python implements regular backup of the mysql database and sends the backup database email

First, let's look at the command to backup the mysql database

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

2. Write Python programs

       BackupsDB.py

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

backup database  

'''
import them
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
# The first parameter determines the time of the task and returns the number of seconds elapsed since a specific time
# The second parameter measures time in some artificial way
schedule = sched.scheduler(time.time, time.sleep);
def backupsDB():
        # If it is linux, change the path
  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]"#The sender's email
  _pwd = "xxxx"#Sender's password
  _to = "[email protected]"#Recipient's email
  # As the name suggests, Multipart is divided into multiple parts
  msg = MIMEMultipart()
  msg["Subject"] = "Mall Database Backup"
  msg["From"] = _user
  msg["To"] = _to
  # ---This is the text part---
  part = MIMEText("Mall Database Backup")
  msg.attach(part)
  #---This is the attachment section---
  # type attachment
  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) # Connect to smtp mail server, the default port is 25
  s.login(_user, _pwd) # log in to the server
  s.sendmail(_user, _to, msg.as_string()) # send mail
  s.close();
def perform_command(cmd, inc):
  # Arrange to run itself again after inc seconds, that is, run periodically
  schedule.enter(inc, 0, perform_command, (cmd, inc));
  os.system(cmd);
  backupsDB();
  sendMail();
def timming_exe(cmd, inc=60):
  # enter is used to schedule the occurrence time of an event, starting at the nth second from now
  schedule.enter(inc, 0, perform_command, (cmd, inc))
  # Keep running until the scheduled time queue becomes empty
  schedule.run()
if __name__ == '__main__':
  print("show time after 10 seconds:");
  timming_exe("echo %time%", 56400);#Backup and send emails every 56400 seconds
  #46400 Basically half a day

then command

py BackupsDB.py

Just run the program.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325216792&siteId=291194637
Recommended