利用python实现数据库的备份、压缩并且删除一个月之前的备份数据

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -*- contact:xupeng.js@gmail.com -*-
# -*- desc:自动备份压缩mysql数据库 -*-

import os,time,sys

databases   =   ['hk_base']
host        =   '192.168.1.188'
user        =   'xupeng'
pwd         =   'xupeng'
port        =   3000
dump        =   '/usr/local/mysql5/bin/mysqldump'
backDir     =   '/home/xp/mysqlback/'   #备份路径 
deleteDay   =   30                      #删除多久之前的备份数据,单位(天)

#删除旧数据
def clear():
    if not os.path.isdir(backDir):
        return 
    files = os.listdir(backDir)
    oldTime = time.time() - deleteDay*57600
    for f in files:
        filePath = backDir+f
        if os.path.isfile(filePath):
            ctime = os.path.getctime(filePath)
            if(ctime < oldTime):
                try:
                    os.remove(filePath)
                except Exception:
                    log("删除旧的备份数据异常")
                    sys.exit()

#数据库备份
def dbDump():
    if not os.path.isdir(backDir):
        try:
            os.makedirs(backDir)
        except Exception:
            log("创建目录失败")
            sys.exit()
            
    backDay = time.strftime("%Y%m%d")
    for database in databases:        
        backName = backDir+database+'.sql'
        sql_command = "%s -u%s -p%s -h%s -P%s %s --skip-opt --add-drop-table --create-options -q -e --set-charset --hex-blob --routines --single-transaction --master-data=2 -B > %s"%(dump,user,pwd,host,port,database,backName)
        try:           
            if (os.system(sql_command) == 0):
                zipName = backDir+database+'_'+backDay+'.zip'
                shell_command = "zip %s %s"%(zipName,backName)            
                if (os.system(shell_command) == 0):
                    os.remove(backName)
                    message = database+"备份压缩成功!"
                    log(message)
                else:
                    message = database+"备份压缩失败!"
                    log(message)
            else:
                message = database+"备份失败!!"
                log(message)
                sys.exit()
        except Exception:
            message = database+"备份异常!!"
            log(message)
            sys.exit()

#记录日志函数
def log(msg):
    datenow = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
    logstr = '%s : %s \n' %(datenow, msg)
    logfile.write(logstr)
    
if __name__ == '__main__':
    logfile = open("/tmp/mysqldump.log", "a")
    clear()
    dbDump()
    logfile.close()