linux数据库备份脚本

部署服务器,需要安装个MySQL,所以有备份数据库数据的定时任务的需求:

写了两种方法,先记录下来,

方法一:

1.编写相应脚本:

time=$(date "+%Y%m%d")

mysqldump  -u*** -p**** test >  /data/test/test${time}.sql

2.编辑crontabding定时任务,然后重启;

1 0 * * *  sh /data/test/test.sh    (每天都执行)

 

方法二:

使用python脚本:

import os
import subprocess
import time
import datetime


DB_USERNAME = "****"
DB_PASSWORD = "****"
PATH = "/data/dbback/bk"
DEFAULT_DB = "law_sh"

def backDb(dbName):
    if(dbName==None):
        dbName=DEFAULT_DB      
    targetPath=PATH + os.sep + dbName + "-" + time.strftime('%Y-%m-%d',time.localtime()) + ".sql"
    command="mysqldump -u" + DB_USERNAME + " -p" + DB_PASSWORD + " " + dbName + " >" + targetPath
    print('execute command : ',command)
    p=subprocess.Popen(command,shell=True,)
    p.wait()
    print("------------- db backup successful ---------")

    delUselessFile()
    print("------------- delete invalid backFile successful ---------")
    return 


def recover(fileName):   
    targetPath=PATH +os.sep+ fileName
    dbName=fileName.split("-")[0]
    command="mysql -u" + DB_USERNAME + " -p" + DB_PASSWORD + " " + dbName + " <" + targetPath
    print('execute command : ',command)
    p=subprocess.Popen(command,shell=True,)
    p.wait()
    print("------------- db recover successful ---------")
    return   

def delUselessFile():
    print('where are you ?')
    files=os.listdir(PATH)
    for delFile in files:
       if isOverDue(delFile):
           os.remove(PATH+os.sep+delFile)
       print('  delete file ',delFile) 
      

def isOverDue(file):
    cpDate=datetime.datetime.now()-datetime.timedelta(days=7)
    dateString = file[file.find("-") + 1:file.find(".")]

    fileDate= datetime.datetime.strptime(dateString,'%Y-%m-%d')
   
    print(fileDate.strftime('%Y-%m-%d'),'   --   ',cpDate.strftime('%Y-%m-%d'))
    if(fileDate<cpDate):
       return True
    else:
       return False  

backDb('law_sh')
backDb('law_pd')

  方法一更加简单,方法二增加成本,但对于这类基本不会改动的脚本,也关系不大,看自己的选择。

 

posted @ 2017-08-08 10:31  it馅儿包子  阅读(257)  评论(0编辑  收藏  举报