美文网首页
备份文件保留最近7天

备份文件保留最近7天

作者: Canon_2020 | 来源:发表于2020-04-20 09:09 被阅读0次
    #!/usr/local/python3
    # -*- coding: utf-8 -*-
    # @Date    : 2018-04-15 09:00:00
    # @Author  : Canon
    # @Link    : https://www.python.org
    # @Version : 3.6.1
    
    """
    python sys.argv[0] sys.argv[1]
    sys.argv[0]: 脚本路径
    sys.argv[1]: 备份测试环境项目的文件夹
    
    执行脚本示例:
    python /home/mirror/BuildDir/PyScript/daily_backup.py oms
    
    """
    
    import os
    import datetime
    import sys
    
    # 打包的文件夹
    dir_name = sys.argv[1].lower()
    
    
    def get_date_list(program):
        """ 获取保留的日期 (最近7天及这四个月 (1, 4, 7, 10) 每月1号) """
        date_list = []
        # 获取最近7天的日期
        date_num = 0
        for n in range(7):
            date_val = datetime.date.today() - datetime.timedelta(days=date_num)
            date_list.append(program + "_" + date_val.strftime('%Y%m%d') + ".tar.gz")
            date_num += 1
    
        # 初始日期
        datestart = datetime.datetime.strptime('2018-01-01','%Y-%m-%d')
        # 当月1号
        num = 1
        month_num = datetime.date.today().replace(day=num)
        # 当日到初始日期相差的月数
        diff = abs((month_num.year - datestart.year) * 12 + (month_num.month - datestart.month) * 1) + 1
        for n in range(diff):
            # 只保留 1, 4, 7, 10 这四个月的备份
            if month_num.strftime('%m') in ['01', '04', '07', '10']:
                date_list.append(program + "_" + month_num.strftime('%Y%m%d') + ".tar.gz")
            month_num = (month_num - datetime.timedelta(num)).replace(day=num)
        return date_list
    
    
    def get_bakfiles(file_dir):
        """ 获取备份目录下的所有文件名 """
        for root, dirs, files in os.walk(file_dir):
            return files
    
    
    def pack_file(proj_dict):
        """ 备份文件 """
        num = int(datetime.datetime.now().strftime("%H"))
        # 备份文件后缀
        suffix = ".tar.gz" 
        # 判断时间在0时到6时,备份日期为昨天
        if num >= 0 and num <= 6:
            now = "_" + str(datetime.date.today()-datetime.timedelta(days=1)).replace("-", "")
        else:
            now = "_" + str(datetime.date.today()).replace("-", "")
        init_path = proj_dict["init_path"]
        proj_name = proj_dict["name"]
        bak_path = proj_dict["bak_path"]
        print("备份项目:{0}".format(proj_name))
        # 备份文件
        bak_file = bak_path + "/" + proj_name + now + suffix
        print("备份文件:{0}".format(bak_file))
        os.system("tar -zcf {0} -C {1} {2}".format(bak_file, init_path, proj_name))
    
    
    proj_list = [
        {
            "name": "PaymentGateway",
            "init_path": "/usr/local/apps/PG",
            "bak_path": "/home/mirror/DailyBak/PaymentGateway"},
        {
            "name": "AutoCheckInterface",
            "init_path": "/usr/local/apps/ACI",
            "bak_path": "/home/mirror/DailyBak/AutoCheckInterface"},
        {
            "name": "AdminSystem",
            "init_path": "/usr/local/apps/AS",
            "bak_path": "/home/mirror/DailyBak/AdminSystem"},
        {
            "name": "NewMerchantSystem",
            "init_path": "/usr/local/apps/NM",
            "bak_path": "/home/mirror/DailyBak/NewMerchantSystem"},
        {
            "name": "oms",
            "init_path": "/usr/local/apps/OMS",
            "bak_path": "/home/mirror/DailyBak/OMS"}
    ]
    
    # 备份项目
    if dir_name == "all":
        for item in proj_list:
            # 备份所有项目
            pack_file(item)
            # 保留15天内及每月1号的备份数据
            for file_name in get_bakfiles(item["bak_path"]):
                if file_name not in get_date_list(item["name"]):
                    # 删除备份数据
                    os.system('rm -rf {}'.format(item["bak_path"] + "/" + file_name))
                    print("删除备份文件:{0}".format(file_name))
    elif dir_name == "paymentgateway":
        # 备份: 支付网关
        pack_file(proj_list[0])
    elif dir_name == "autocheckinterface":
        # 备份: 对账平台
        pack_file(proj_list[1])
    elif dir_name == "adminsystem":
        # 备份: 管理后台
        pack_file(proj_list[2])
    elif dir_name == "newmerchantsystem":
        # 备份: 账户后台
        pack_file(proj_list[3])
    elif dir_name == "oms":
        # 备份: OMS 项目
        pack_file(proj_list[4])
    
    

    相关文章

      网友评论

          本文标题:备份文件保留最近7天

          本文链接:https://www.haomeiwen.com/subject/emctwctx.html