The Seven Year Itch.

MENU

备份博客数据的小脚本(更新了下)

October 16, 2017 • Read: 468 • 数据库,Python

用python3执行的哈,python2试了一次是OK的!


"""
@ Created by Seven on  2018/09/14
"""
import os
import time

class BackupDb:
    def __init__(self,host='0.0.0.0',port=3306):
        self.datetime = time.strftime('%Y-%m-%d_%M:%H:%S')
        self.backname = 'typecho_sql-{}.sql'.format(self.datetime)
        self.__remove = 'cd path && rm -rf *.sql'
        os.system(self.__remove)
        time.sleep(2)
        self.__cmd = 'mysqldump -h {}  -u root -p{} --port {} typecho > /home/backup/{}'.format(host,password,port,self.backname)
        os.system(self.__cmd)

    def send_email(self):
        user = 'email'
        try:
            import yagmail
            email = yagmail.SMTP(user='',password='',host='',port='')
            try:
                email.send(
                    user,
                    subject='Soo9s Blog  Backup DBs',
                    attachments=['path'+ self.backname]
            )
                message = {'time':self.datetime,'send_status':'BACKUP AND SENDMAIL SUCCESS!'}
                print(message)
            except Exception as e:
                print("{'msg':'send email error!'}")
        except Exception:
            print('`yagmail` install.... ')
            os.system('pip3 install yagmail')
        

back = BackupDb()
back.send_email()

pip install yagmail
import os
import time
import datetime
import yagmail
DATETIME = time.strftime('%Y-%m-%d_%M:%H:%S')
BACKUPNAME = 'typecho_sql' + "-" + DATETIME + ".sql"
def backupDB():
    #remove = 'rm -rf /home/backup/ *.sql' 自己做的BUG 哭着也要吃完!
    remove = 'cd /home/backup/ && rm -rf *.sql'
    os.system(remove)
    time.sleep(2)
    cmdString = 'mysqldump -u root -password. typecho > /home/backup/' + BACKUPNAME
    os.system(cmdString)

def sendMail():
    user = 'username@qq.com'
    Email = yagmail.SMTP(user='username@163.com',password='nicai?',host='smtp.163.com',port='465')
    Email.send(user,subject='Soo9s Blog  Backup DBs',attachments=['/home/backup/'+ BACKUPNAME])
    print "BACKUP AND SENDMAIL SUCCESS!"+DATETIME
if __name__ == '__main__':
    backupDB()
    sendMail()

前面忘记贴定时计划了。。
先启动crontab 没有的话需要安装一下
然后进入编辑模式 crontab -e
我定制的计划是每周周五15点备份,并发送到我的邮件
backup

Archives QR Code
QR Code for this page
Tipping QR Code