python调用windows robocopy命令备份还原文件

本文介绍了一个Python类,利用Windows的robocopy命令进行全量和增量备份,以及文件恢复操作。该类通过MD5校验确保文件内容一致性,并将备份和恢复信息记录到数据库。
摘要由CSDN通过智能技术生成
import subprocess, sqlite3,os, time, hashlib,datetime,shutil
class WindowsBackup:
    def __init__(self, origin_path, to_path, name, is_full, log_path):
        self.conn = sqlite3.connect('ybm.db')
        self.cursor = self.conn.cursor()
        self.origin_path =origin_path
        self.to_path = to_path
        self.name = name
        self.is_full = is_full
        self.log_path = log_path

    def backup(self, task_id):
        afiles = []
        bfiles = []

        # 判断备份文件路径是否存在,如不存在,则创建
        if os.path.exists(self.to_path):
            # return True
            pass

        else:
            os.mkdir(self.to_path)

        # 获取日志文件路径
        logs_path = os.path.abspath(os.path.join(self.log_path,'task_id.txt'))




        # 获取备份文件名
        path = os.path.normpath(self.to_path)
        filename1 = path.split(os.sep)[-1]


        # 需要备份的源文件大小
        beisize = 0
        for root, dirs, files in os.walk(self.origin_path):
            for file in files:
                filename = os.path.join(root, file)
                beisize += os.path.getsize(filename)

                #  使用MD5判断备份文件与源文件内容是否相同
                hasher1 = hashlib.md5()
                afile1 = open(filename, 'rb')
                buf1 = afile1.read()
                hasher1.update(buf1)
                c = hasher1.hexdigest()
                afiles.append(c)

        # 如果self.is_full等于零,那么备份是全量备份
        if self.is_full == 0:

            # 备份开始时间
            start = time.localtime()
            subprocess.call([r'robocopy', self.origin_path, self.to_path, self.na
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值