Mysql備份腳本python編寫

#!/usr/bin/env python
#-*- coding: UTF-8 -*- 
##############################################################
#
# Date: 2017/09/22 
# Filename: BackupMySQL.py
# Description: backup mysql files,base percona xtrabackup
#
# 備份mysql數據庫數據,在主庫進行數據同步備份:10.99.10.22
# 備份的數據存儲目錄: /data/backup/mysqlbak/
# 備份策略是天天備份一次,以當天日期命名的目錄,如:20170922
# 保留最近7天的備份數據,可配置
##############################################################


# Import required python libraries
import os 
import sys 
import time
import logging 
import datetime 
import subprocess 

logging.basicConfig(level=logging.DEBUG, 
                format='[%(asctime)s]  [%(levelname)s] %(message)s', 
                datefmt='%Y-%m-%d %H:%M:%S', 
                filename='/software/scrpits/backupMysql/backupMysql.log', 
                filemode='a') 

# 配置數據庫鏈接信息
DB_HOST = '10.99.10.22'
DB_USER = 'bakuser'
DB_USER_PASS = 'xxxxxxxx'

# 配置本地保留多少天的數據備份,默認保留7天
DataSave = 7

# 配置備份的基礎目錄
BackupPath = '/data/backup/mysqlbak/'

DayTime = time.strftime('%Y%m%d')
TodayBackupPath =  BackupPath + DayTime


def Check():
    '''備份前檢查,若是目錄存在則退出,不然建立備份目錄'''
    if os.path.exists(TodayBackupPath):
        res = 'The backup directory already exists: %s. exit ...' % TodayBackupPath
        print res
        logging.error(res)
        sys.exit()
    else:
        os.makedirs(TodayBackupPath)
        res1 = "creating backup folder %s " % TodayBackupPath
        logging.info(res1)


def BackupDB():
    '''備份數據庫,定義備份指令,參數'''
    Check()

    logging.info('Start backing up the database.')
    iArgs = "--slave-info  --no-timestamp"
    BackupCmd = "/usr/bin/innobackupex %s --host=%s  --user=%s --password=%s %s "  \
                   %  (iArgs, DB_HOST, DB_USER, DB_USER_PASS, TodayBackupPath) 
    p = subprocess.Popen(BackupCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    stdout,stderr = p.communicate()
    logging.info(stdout)
    logging.info(stderr)
    logging.info('The database backup is complete')

def GetTimePoint(days):
    ''' 返回須要刪除的時間點 '''
    CurrTime = time.time()
    DelTime = 3600*24*int(days)
    TimePoint = CurrTime - DelTime
    return TimePoint


def CheckDir(cdir):
    ''' 刪除文件夾的函數 '''
    try:
        if os.path.isdir(cdir):
            os.rmdir(cdir)
            s = 'remove dir %s succ ...' % cdir
            logging.info(s)
    except Exception as e:
        s = 'remove dir %s FAIL !!! %s' % (cdir, e)
        logging.error(s)
    

def CleanOld(beforeTime, path):
    ''' 遍歷備份目錄,獲取目錄mtime時間,比對時間戳,刪除以前目錄 '''
    logging.warn('Start cleaning up old backup data...')
    for eachdir in os.listdir(path):
        f = path + eachdir
        lastMtime = os.stat(f).st_mtime
        if lastMtime <= beforeTime:
            CheckDir(f)            
    
if __name__ == '__main__': 
    BackupDB()    
    t = GetTimePoint(DataSave)
    CleanOld(t, BackupPath) 
相關文章
相關標籤/搜索