Python3 实现完全备份、增量备份目录以及文件

import os
from time import strftime
import pickle as p
import tarfile
import hashlib
#运行脚本,每周四进行完全备份,其他时间进行增量备份。

src_dir = '/root/security'                            #定义源目录
dst_dir = '/tmp/mybackup'                             #定义目标目录
md5_file = '/tmp/mybackup/md5.data'                   #采用MD5进行校验
nowdate = strftime('%Y-%m-%d')


def check_md5(fname):                      #定义MD5处理函数,每次处理4096字节更新MD5值
    m = hashlib.md5()
    with open(fname, 'rb') as fobj:
        data = fobj.read(4096)
        if data:
            m.update(data)
    return m.hexdigest()


def full_backup(src_dir, dst_dir, md5_file):
    md5_dict = {}
    fname = 'full_backup' + os.path.basename(src_dir) + '-' + nowdate + '.tar.gz'
    path_file = os.path.join(dst_dir, fname)
    tar = tarfile.open(path_file, 'w:gz')
    tar.add(src_dir)
    tar.close()
    for path, folders, files in os.walk(src_dir):   #采用os的walk遍历目录
        for each_file in files:
            key = os.path.join(path, each_file)
            md5_dict[key] = check_md5(key)
    with open(md5_file, 'wb') as fobj:
        p.dump(md5_dict, fobj)


def incr_backup(src_dir, dst_dir, md5_file):
    fname = 'incr_backup' + os.path.basename(src_dir) + '-' + nowdate + '.tar.gz'
    path_file = os.path.join(dst_dir, fname)
    with open(md5_file, 'rb') as fobj:
        ori_md5_dict = p.load(fobj)
    new_md5_dict = {}
    tar = tarfile.open(path_file, 'w:gz')
    for path, folders, files in os.walk(src_dir):
        for each_file in files:
            key = os.path.join(path, each_file)
            new_md5_dict[key] = check_md5(key)
            if ori_md5_dict.get(key) != new_md5_dict[key]:
                tar.add(key)
    tar.close()


if __name__ == '__main__':
    if not os.path.exists(dst_dir):
        os.mkdir(dst_dir)
    if strftime('%a') == 'Thu':
        full_backup(src_dir, dst_dir, md5_file)
    else:
        incr_backup(src_dir, dst_dir, md5_file)

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值