# -*- coding: utf-8 -*- """ U盘备份工具 (Udisk Backup for Windows) —— 加固版 ================================================= 在原版基础上重写了备份引擎,针对"多次备份后备份数据崩坏 / 备份内容过期 / 备份文件被误删" 这一类问题做加固。原版 v1 见 legacy/usb_backup_v1.py,缺陷复现见 tests/repro_v1_defects.py。 设计要点(对应 v1 的问题): 1. 不信任"大小 + 修改时间":默认复制后回读并做 SHA-256 校验,校验失败保留旧文件、报失败。 2. 归档前落盘:写入后 flush + os.fsync,结束前尝试 FlushFileBuffers,避免"提示完成时数据还在缓存里"。 3. 不往脏卷/损坏卷上写:目标卷 Dirty 或需要完整修复时直接拒绝,要求先 chkdsk /f。 4. 清理(镜像同步)前必须"扫描完整 + 无失败":扫描有任何一个目录读不到,就不删任何东西。 5. 默认不物理删除:多余文件移入 <目标>/.udbak-quarantine/<时间戳>/,可回滚;彻底删除需显式勾选。 6. 路径比较全部按 Windows 规则大小写无关(os.path.normcase),不再把 Spec.TXT 和 spec.txt 当成两个文件。 7. 临时文件用 ".udbak-tmp-<随机>" 生成且带排除规则,不再用 "<目标名>~bak" 覆盖真实文件。 8. 全程长路径(\\?\)支持,扫描/清理/复制使用同一套路径规则;源与目标互相嵌套直接拒绝。 9. 预检:空间不足、FAT32/exFAT 单文件 4GB 上限、目标在源内、源在目标内、目标是源本身。 仅使用标准库(tkinter / ctypes / hashlib)。 """ import ctypes import errno import hashlib import os import shutil import stat import sys import threading import time import tkinter as tk import uuid from tkinter import ttk, messagebox, filedialog # ==================== 常量 ==================== APP_NAME = "U盘备份工具" APP_VERSION = "2.0" BACKUP_ROOT = r"E:\U盘备份" BUF_SIZE = 4 * 1024 * 1024 # 4MB 复制缓冲区 HASH_BUF = 4 * 1024 * 1024 MTIME_TOLERANCE = 2.0 # FAT 时间精度 2 秒 TMP_DIR = ".udbak-tmp" QUARANTINE_DIR = ".udbak-quarantine" QUARANTINE_RETAIN_DAYS = 7 FAT32_MAX_FILE = 4 * 1024 ** 3 - 1 # 系统目录:无法读取也没意义,直接跳过(全量镜像时也不删除它们) SYSTEM_DIRS = { "System Volume Information", "$RECYCLE.BIN", "RECYCLER", ".Trash-1000", "SystemVolumeInformation", } SYSTEM_DIRS_LC = {d.lower() for d in SYSTEM_DIRS} class BackupError(Exception): """预检失败 / 致命错误(带用户可读原因)""" # ==================== 路径 & 文件系统工具 ==================== def _long(path): """转换为 Win32 长路径形式 (\\\\?\\),支持 >260 字符。""" if os.name != "nt": return path if path.startswith("\\\\?\\"): return path p = os.path.abspath(path) if p.startswith("\\\\"): # UNC: \\server\share return "\\\\?\\UNC" + p[1:] return "\\\\?\\" + p def _plain(path): r"""去掉 \\?\ 前缀,便于日志展示。""" if path.startswith("\\\\?\\UNC"): return "\\\\" + path[8:] if path.startswith("\\\\?\\"): return path[4:] return path def _norm(path): """Windows 语义下用于比较的规范形式(大小写无关)。""" return os.path.normcase(os.path.abspath(_plain(path))) def _is_within(child, parent): """child 是否等于 parent 或位于其内部(大小写无关,按路径组件判断)。""" c = _norm(child).rstrip("\\") + "\\" p = _norm(parent).rstrip("\\") + "\\" return c.startswith(p) def _rel(path, root): return os.path.relpath(_plain(path), _plain(root)) def _ensure_dir(path): os.makedirs(_long(path), exist_ok=True) def _clear_readonly(path): try: os.chmod(_long(path), stat.S_IWRITE | stat.S_IREAD) except OSError: pass def _safe_stat(path, follow_symlinks=False): try: return os.stat(_long(path), follow_symlinks=follow_symlinks) except OSError: return None def _fmt_size(n): n = float(n) for unit in ("B", "KB", "MB", "GB", "TB"): if n < 1024: return "%.1f %s" % (n, unit) n /= 1024 return "%.1f PB" % n def _hash_file(path, buf=HASH_BUF): """SHA-256;读失败返回 None。""" h = hashlib.sha256() try: with open(_long(path), "rb") as f: while True: chunk = f.read(buf) if not chunk: break h.update(chunk) return h.hexdigest() except OSError: return None # ---------- 卷信息 / 脏卷检测 / 落盘 ---------- def get_volume_info(drive): """返回 dict(fs=..., label=..., total=..., free=..., serial=...)""" info = {"fs": "", "label": "", "total": 0, "free": 0, "serial": 0} root = drive if drive.endswith("\\") else drive + "\\" try: label = ctypes.create_unicode_buffer(261) fsname = ctypes.create_unicode_buffer(261) serial = ctypes.c_ulong(0) ok = ctypes.windll.kernel32.GetVolumeInformationW( ctypes.c_wchar_p(root), label, 261, ctypes.byref(serial), None, None, fsname, 261) if ok: info["label"] = label.value info["fs"] = fsname.value info["serial"] = serial.value except (OSError, AttributeError): pass try: total = ctypes.c_ulonglong(0) free = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(root), None, ctypes.byref(total), ctypes.byref(free)) info["total"] = total.value info["free"] = free.value except (OSError, AttributeError): pass return info FSCTL_IS_VOLUME_DIRTY = 0x0009007C GENERIC_READ = 0x80000000 FILE_SHARE_READ = 0x1 FILE_SHARE_WRITE = 0x2 OPEN_EXISTING = 3 INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value def is_volume_dirty(root_path): """卷是否处于 Dirty 状态(未正常卸载 / 文件系统需要修复)。None=无法判断。 NTFS 走 FSCTL_IS_VOLUME_DIRTY;FAT32/exFAT 上该 IOCTL 返回 ERROR_INVALID_FUNCTION, 退化为 fsutil dirty query(无需管理员,但部分卷会拒绝访问)。 """ if os.name != "nt": return None drive = os.path.splitdrive(os.path.abspath(_plain(root_path)))[0] if not drive: return None try: handle = ctypes.windll.kernel32.CreateFileW( ctypes.c_wchar_p("\\\\.\\" + drive), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, 0, None) except (OSError, AttributeError): handle = None if handle not in (None, INVALID_HANDLE_VALUE): try: buf = ctypes.create_string_buffer(16) returned = ctypes.c_ulong(0) ok = ctypes.windll.kernel32.DeviceIoControl( ctypes.c_void_p(handle), FSCTL_IS_VOLUME_DIRTY, None, 0, buf, 16, ctypes.byref(returned), None) if ok and returned.value >= 4: flags = ctypes.cast(buf, ctypes.POINTER(ctypes.c_ulong))[0] return bool(flags & 1) finally: ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(handle)) # FAT/exFAT 回退:fsutil dirty query try: import subprocess out = subprocess.run(["fsutil", "dirty", "query", drive], capture_output=True, timeout=10, creationflags=0x08000000) # CREATE_NO_WINDOW text = (out.stdout or b"").decode("mbcs", "replace").strip() if not text: text = (out.stderr or b"").decode("mbcs", "replace").strip() low = text.lower() if "not dirty" in low or "不是脏" in text or "不脏" in text: return False if "is dirty" in low or "已损坏" in text or "脏" in text: return True return None except (OSError, subprocess.SubprocessError): return None def flush_volume(root_path): """尽量把目标卷的元数据刷到设备(失败不影响主流程)。""" if os.name != "nt": return False try: handle = ctypes.windll.kernel32.CreateFileW( ctypes.c_wchar_p(_long(root_path)), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, 0x02000000, # FILE_FLAG_BACKUP_SEMANTICS:打开目录句柄 None) if handle == INVALID_HANDLE_VALUE or handle is None: return False try: return bool(ctypes.windll.kernel32.FlushFileBuffers(ctypes.c_void_p(handle))) finally: ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(handle)) except (OSError, AttributeError): return False # ==================== USB 检测 ==================== def get_usb_drives(include_fixed=False): """返回可移动磁盘(U盘)的盘符列表;include_fixed 时也包含固定磁盘。""" drives = [] bitmask = ctypes.windll.kernel32.GetLogicalDrives() for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": if bitmask & 1: drive = "%s:\\" % letter dtype = ctypes.windll.kernel32.GetDriveTypeW(drive) if dtype == 2: drives.append(drive) elif include_fixed and dtype == 3: drives.append(drive) bitmask >>= 1 return drives def get_volume_name(drive): buf = ctypes.create_unicode_buffer(261) ctypes.windll.kernel32.GetVolumeInformationW( ctypes.c_wchar_p(drive), buf, 261, None, None, None, None, 0) return buf.value if buf.value else "(无卷标)" def get_drive_info(drive): total = ctypes.c_ulonglong(0) free = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(drive), None, ctypes.byref(total), ctypes.byref(free)) return total.value, free.value # ==================== 备份引擎 ==================== class BackupEngine: """全量镜像 / 增量备份引擎(无 GUI 依赖,可单独测试)。""" def __init__(self, source, dest, mode="full", verify=True, deep_verify=False, hard_delete=False, progress_callback=None, log_callback=None, allow_dirty_volume=False, purge_quarantine=True): self.source = os.path.abspath(source) self.dest = os.path.abspath(dest) self.mode = mode self.verify = verify self.deep_verify = deep_verify self.hard_delete = hard_delete self.progress_callback = progress_callback or (lambda p, s: None) self.log_callback = log_callback or (lambda msg: None) self.allow_dirty_volume = allow_dirty_volume self.purge_quarantine = purge_quarantine self.cancelled = False self.failures = [] # 致命/单文件失败 self.warnings = [] self.scan_errors = [] # 扫描阶段读不到的目录 self.scan_complete = True self.stats = { "files_scanned": 0, "dirs_scanned": 0, "planned": 0, "copied": 0, "skipped": 0, "verified": 0, "deleted": 0, "quarantined": 0, "bytes": 0, "failed": 0, "duration": 0.0, } self._written = set() self._dir_cache = {} # ---------- 基础 ---------- def cancel(self): self.cancelled = True def _log(self, msg): self.log_callback(msg) def _fail(self, msg): self.failures.append(msg) self._log(" [失败] " + msg) def _warn(self, msg): self.warnings.append(msg) self._log(" [警告] " + msg) # ---------- 预检 ---------- def preflight(self): if not os.path.isdir(_long(self.source)): raise BackupError("源目录不存在或不可访问:%s" % self.source) if _is_within(self.dest, self.source): raise BackupError( "目标目录位于源目录内部:\n 源 %s\n 目标 %s\n" "这样备份会被当成源文件再次备份,逐次嵌套并最终撑爆磁盘,已拒绝执行。" % (self.source, self.dest)) if _is_within(self.source, self.dest): raise BackupError( "源目录位于目标目录内部:\n 源 %s\n 目标 %s\n" "全量镜像清理会删除源目录,已拒绝执行。" % (self.source, self.dest)) vol = get_volume_info(self.dest) if vol["fs"]: self._log("目标卷: %s 文件系统: %s 可用: %s / %s" % ( os.path.splitdrive(self.dest)[0], vol["fs"], _fmt_size(vol["free"]), _fmt_size(vol["total"]))) dirty = is_volume_dirty(self.dest) if dirty: msg = ("目标卷处于 Dirty(未正常卸载/文件系统需要修复)状态:%s\n" "在这种卷上继续写会覆盖已损坏的 FAT/目录区,越备越坏。\n" "请先以管理员身份执行: chkdsk %s /f\n然后再备份。" % (os.path.splitdrive(self.dest)[0], os.path.splitdrive(self.dest)[0])) if not self.allow_dirty_volume: raise BackupError(msg) self._warn(msg) elif dirty is False: self._log("目标卷状态: 干净") if vol["fs"].upper() in ("FAT32", "FAT", "EXFAT"): self._log("注意: %s 无日志、无校验,异常掉线后必须 chkdsk 修复;" "本工具会在结束时落盘并校验每个文件。" % vol["fs"]) # 卷健康检查通过后才创建目标目录,避免往坏盘上写任何东西 if not os.path.isdir(_long(self.dest)): try: _ensure_dir(self.dest) except OSError as e: raise BackupError("目标目录不存在且无法创建:%s\n%s" % (self.dest, e)) # ---------- 扫描 ---------- def _scan(self): """扫描源目录。返回 (files, dirs):files=[(abs, rel, size, mtime_ns)]""" self._log("[备份] 正在扫描文件...") files, dirs = [], [] stack = [(self.source, "")] while stack: absdir, rel = stack.pop() if self.cancelled: break try: with os.scandir(_long(absdir)) as it: for entry in it: try: is_dir = entry.is_dir(follow_symlinks=False) except OSError: is_dir = False name = entry.name if is_dir: if name.lower() in SYSTEM_DIRS_LC: continue child_rel = os.path.join(rel, name) if rel else name dirs.append(child_rel) stack.append((os.path.join(absdir, name), child_rel)) else: st = None try: st = entry.stat(follow_symlinks=False) except OSError as e: self.scan_complete = False self.scan_errors.append("%s (%s)" % ( os.path.join(absdir, name), e.strerror or e)) child_rel = os.path.join(rel, name) if rel else name files.append((os.path.join(absdir, name), child_rel, st.st_size if st else -1, st.st_mtime_ns if st else 0)) except OSError as e: # 关键:扫描不完整时,绝不进入镜像清理 self.scan_complete = False self.scan_errors.append("%s (%s)" % (_plain(absdir), e.strerror or e)) self.stats["files_scanned"] = len(files) self.stats["dirs_scanned"] = len(dirs) self._log("[扫描完成] 文件 %d 个,目录 %d 个" % (len(files), len(dirs))) if self.scan_errors: for err in self.scan_errors[:20]: self._warn("无法读取: " + err) if len(self.scan_errors) > 20: self._warn("…… 共 %d 项无法读取" % len(self.scan_errors)) return files, dirs # ---------- 比较 ---------- def _need_copy(self, src, dst, size, mtime_ns): """返回 (需要复制?, 是否已校验)。""" st = _safe_stat(dst) if st is None or not stat.S_ISREG(st.st_mode): return True, False if size >= 0 and st.st_size != size: return True, False same_time = abs(st.st_mtime_ns - mtime_ns) <= int(MTIME_TOLERANCE * 1e9) if same_time and not self.deep_verify: return False, False h_src = _hash_file(src) if h_src is None: return True, False h_dst = _hash_file(dst) if h_dst is None: return True, False self.stats["verified"] += 1 return h_src != h_dst, True # ---------- 大小写同步 ---------- def _actual_names(self, d): key = os.path.normcase(d) names = self._dir_cache.get(key) if names is None: names = {} try: with os.scandir(_long(d)) as it: for e in it: names.setdefault(e.name.lower(), e.name) except OSError: pass self._dir_cache[key] = names return names def _sync_name(self, dst): """目标已存在但大小写与源不同时,改成源的名字(Windows 大小写不敏感)。""" d, want = os.path.split(dst) actual = self._actual_names(d).get(want.lower()) if actual is None or actual == want: return try: os.replace(_long(os.path.join(d, actual)), _long(dst)) self._dir_cache[os.path.normcase(d)][want.lower()] = want self._log(" 修正大小写: %s -> %s" % (actual, want)) except OSError as e: self._warn("修正大小写失败 %s: %s" % (want, e)) # ---------- 复制 ---------- def _tmp_root(self): return os.path.join(self.dest, TMP_DIR) def _tmp_path(self, dst): """临时文件放在 <目标>/.udbak-tmp/<随机>/ 下: 既不与任何真实文件名冲突,同卷 rename 又是原子的。""" name = os.path.basename(dst) if len(name) > 120: stem, ext = os.path.splitext(name) name = stem[:100] + "-" + uuid.uuid4().hex[:6] + ext[:16] return os.path.join(self._tmp_root(), uuid.uuid4().hex[:8], name) def _cleanup_tmp_root(self): """备份结束后清掉自己的临时目录(不留垃圾,也不参与镜像同步)。""" root = self._tmp_root() if not os.path.isdir(_long(root)): return try: for name in os.listdir(_long(root)): shutil.rmtree(_long(os.path.join(root, name)), ignore_errors=True) os.rmdir(_long(root)) except OSError: pass def _purge_tmp(self): root = self._tmp_root() if not os.path.isdir(_long(root)): return limit = time.time() - 3600 try: for name in os.listdir(_long(root)): p = os.path.join(root, name) st = _safe_stat(p) if st and st.st_mtime < limit: shutil.rmtree(_long(p), ignore_errors=True) self._log(" 清理上次残留的临时文件: %s" % name) except OSError: pass def _copy_one(self, src, dst, size, mtime_ns): """复制单个文件:写临时文件 → 校验 → 设置时间 → 原子替换。""" dstdir = os.path.dirname(dst) if not os.path.isdir(_long(dstdir)): _ensure_dir(dstdir) # 目标位置若是目录而同名源是文件,先把目录移入隔离区 if os.path.isdir(_long(dst)) and not os.path.islink(_long(dst)): self._quarantine(dst, reason="类型冲突(目录->文件)") tmp = self._tmp_path(dst) _ensure_dir(os.path.dirname(tmp)) h = hashlib.sha256() try: with open(_long(src), "rb") as fsrc, open(_long(tmp), "wb") as fdst: while True: chunk = fsrc.read(BUF_SIZE) if not chunk: break h.update(chunk) fdst.write(chunk) fdst.flush() os.fsync(fdst.fileno()) got = os.path.getsize(_long(tmp)) if size >= 0 and got != size: raise BackupError("复制长度不一致(源 %d 字节,写入 %d 字节)" % (size, got)) if self.verify: h_disk = _hash_file(tmp) if h_disk is None: raise BackupError("回读校验失败:无法读取临时文件") if h_disk != h.hexdigest(): raise BackupError("SHA-256 校验不一致(源与落盘内容不同,介质可能有问题)") self.stats["verified"] += 1 try: os.utime(_long(tmp), ns=(mtime_ns, mtime_ns)) except OSError: pass _clear_readonly(tmp) if os.path.exists(_long(dst)): _clear_readonly(dst) os.replace(_long(tmp), _long(dst)) # 同卷原子替换,断电不会留半个文件 self._written.add(_norm(dst)) return True finally: if os.path.exists(_long(tmp)): try: _clear_readonly(tmp) os.remove(_long(tmp)) except OSError: pass # ---------- 隔离区 ---------- def _quarantine_root(self): return os.path.join(self.dest, QUARANTINE_DIR) def _quarantine(self, path, reason=""): """把多余条目移入隔离区(保留 7 天),不物理删除。""" stamp = time.strftime("%Y%m%d-%H%M%S") rel = _rel(path, self.dest) target = os.path.join(self._quarantine_root(), stamp, rel) os.makedirs(_long(os.path.dirname(target)), exist_ok=True) try: if os.path.isdir(_long(path)) and not os.path.islink(_long(path)): if os.path.exists(_long(target)): target += "-" + uuid.uuid4().hex[:6] os.replace(_long(path), _long(target)) else: _clear_readonly(path) os.replace(_long(path), _long(target)) self.stats["quarantined"] += 1 self._log(" 移入隔离区: %s%s" % (rel, (" [" + reason + "]") if reason else "")) return True except OSError as e: self._fail("移入隔离区失败 %s: %s" % (rel, e)) return False def _remove(self, path): """物理删除(仅当用户显式选择"彻底删除")。""" try: if os.path.isdir(_long(path)) and not os.path.islink(_long(path)): for root, _dirs, files in os.walk(_long(path)): for fn in files: _clear_readonly(os.path.join(root, fn)) shutil.rmtree(_long(path), ignore_errors=False) else: _clear_readonly(path) os.remove(_long(path)) self.stats["deleted"] += 1 self._log(" 已删除: %s" % _rel(path, self.dest)) return True except OSError as e: self._fail("删除失败 %s: %s" % (_rel(path, self.dest), e)) return False def _purge_quarantine(self): root = self._quarantine_root() if not os.path.isdir(_long(root)): return limit = time.time() - QUARANTINE_RETAIN_DAYS * 86400 try: for name in os.listdir(_long(root)): p = os.path.join(root, name) st = _safe_stat(p) if st and st.st_mtime < limit: shutil.rmtree(_long(p), ignore_errors=True) self._log(" 清理过期隔离区: %s" % name) except OSError: pass # ---------- 清理(镜像同步) ---------- def _cleanup(self, src_files, src_dirs): if not self.scan_complete: self._warn("扫描不完整,跳过清理阶段(不会删除备份中的任何文件)") return if self.failures: self._warn("存在复制失败,跳过清理阶段(避免误删备份)") return if self.cancelled: self._warn("已取消,跳过清理阶段") return self._log("[全量备份] 正在比对多余文件...") src_file_set = {os.path.normcase(rel) for _a, rel, _s, _m in src_files} src_dir_set = {os.path.normcase(d) for d in src_dirs} stale = [] stack = [(self.dest, "")] while stack: absdir, rel = stack.pop() try: with os.scandir(_long(absdir)) as it: for entry in it: name = entry.name if not rel and name in (QUARANTINE_DIR, TMP_DIR): continue # 工具自身目录,不参与镜像清理 child_rel = os.path.join(rel, name) if rel else name child_abs = os.path.join(absdir, name) try: is_dir = entry.is_dir(follow_symlinks=False) except OSError: is_dir = False if is_dir: if name.lower() in SYSTEM_DIRS_LC: continue if os.path.normcase(child_rel) not in src_dir_set: stale.append(child_abs) else: stack.append((child_abs, child_rel)) else: if os.path.normcase(child_rel) not in src_file_set: stale.append(child_abs) except OSError as e: self._warn("目标目录读取失败,清理阶段跳过: %s (%s)" % (_plain(absdir), e.strerror or e)) return # 深的先处理;整棵目录被移走时其子项自然不再单独处理 stale.sort(key=lambda p: p.count(os.sep), reverse=True) n = len(stale) for i, path in enumerate(stale): if self.cancelled: break if not os.path.exists(_long(path)): continue if self.hard_delete: self._remove(path) else: self._quarantine(path) if n: self.progress_callback(90 + int((i + 1) / n * 10), "清理中... %d/%d" % (i + 1, n)) self._log("[清理完成] 多余条目 %d 个(%s)" % (n, "已彻底删除" if self.hard_delete else "已移入隔离区")) # ---------- 主流程 ---------- def run(self): started = time.time() self.preflight() if self.purge_quarantine and not self.hard_delete: self._purge_quarantine() self._purge_tmp() files, dirs = self._scan() if self.cancelled: return self._report(started, ok=False, message="已取消") # 预先建好目录,保证空目录也同步 for rel in dirs: _ensure_dir(os.path.join(self.dest, rel)) # 空间预检 vol = get_volume_info(self.dest) need = 0 big = [] plan = [] total = len(files) or 1 self._log("[比对] 正在计算需要复制的文件...") for idx, (abs_p, rel, size, mtime_ns) in enumerate(files): if self.cancelled: return self._report(started, ok=False, message="已取消") if size < 0: continue if size > FAT32_MAX_FILE and vol["fs"].upper() in ("FAT32", "FAT", "EXFAT"): big.append((rel, size)) continue need_copy, _checked = self._need_copy(abs_p, os.path.join(self.dest, rel), size, mtime_ns) if need_copy: plan.append((abs_p, rel, size, mtime_ns)) need += size else: self.stats["skipped"] += 1 self._sync_name(os.path.join(self.dest, rel)) if (idx + 1) % 50 == 0: self.progress_callback(int((idx + 1) / total * 30), "比对中... %d/%d" % (idx + 1, total)) if big: raise BackupError( "以下文件超过 %s 单文件 4GB 上限,无法备份到该卷:\n%s" % (vol["fs"], "\n".join(" %s (%s)" % (r, _fmt_size(s)) for r, s in big[:5]))) if need and vol["free"] and need > vol["free"]: raise BackupError("空间不足:需要约 %s,目标卷可用 %s" % (_fmt_size(need), _fmt_size(vol["free"]))) if need and vol["free"]: self._log("[计划] 需复制 %d 个文件 / %s,可用 %s" % (len(plan), _fmt_size(need), _fmt_size(vol["free"]))) else: self._log("[计划] 没有需要复制的文件(%d 个文件全部一致)" % self.stats["skipped"]) # 复制 done = 0 for abs_p, rel, size, mtime_ns in plan: if self.cancelled: return self._report(started, ok=False, message="已取消") try: self._copy_one(abs_p, os.path.join(self.dest, rel), size, mtime_ns) self.stats["copied"] += 1 self.stats["bytes"] += size except (OSError, BackupError) as e: self._fail("复制失败 %s: %s" % (rel, e)) done += 1 if len(plan) and (done % 5 == 0 or done == len(plan)): self.progress_callback(30 + int(done / len(plan) * 60), "复制中... %d/%d" % (done, len(plan))) # 清理多余文件(仅全量 + 扫描完整 + 无失败) if self.mode == "full": self._cleanup(files, dirs) else: self._log("[增量备份] 不删除目标中多余的文件") # 清掉临时目录,再落盘 self._cleanup_tmp_root() flushed = flush_volume(self.dest) self._log("[落盘] %s" % ("已 FlushFileBuffers" if flushed else "文件均已 fsync")) self.progress_callback(100, "完成") return self._report(started, ok=not self.failures) def _report(self, started, ok, message=""): self.stats["failed"] = len(self.failures) self.stats["duration"] = time.time() - started s = self.stats head = "[完成]" if ok else "[未完成]" self._log("%s 复制 %d,跳过 %d,隔离 %d,删除 %d,校验 %d,失败 %d,用时 %.1fs" % (head, s["copied"], s["skipped"], s["quarantined"], s["deleted"], s["verified"], s["failed"], s["duration"])) if message: self._log(" " + message) if self.failures: for f in self.failures[:50]: self._log(" 失败: " + f) if len(self.failures) > 50: self._log(" …… 共 %d 项失败" % len(self.failures)) if ok: self._log(" 现在可以安全弹出磁盘(已落盘)。") return ok, dict(s, failures=list(self.failures), warnings=list(self.warnings), scan_complete=self.scan_complete, message=message) # ==================== 应用界面 ==================== def resource_path(relative): if hasattr(sys, "_MEIPASS"): return os.path.join(sys._MEIPASS, relative) return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative) class BackupApp: def __init__(self): self.root = tk.Tk() self.root.title("%s v%s" % (APP_NAME, APP_VERSION)) self.root.geometry("720x640") self.root.resizable(True, True) try: ico = resource_path("icon.ico") if os.path.exists(ico): self.root.iconbitmap(ico) except Exception: pass self.engine = None self.backup_thread = None self.selected_drive = None self.current_mode = "full" self._build_ui() self.refresh_drives() def _build_ui(self): top = ttk.Frame(self.root, padding=10) top.pack(fill=tk.X) ttk.Label(top, text="选择要备份的U盘:", font=("", 10, "bold")).pack(side=tk.LEFT) self.var_include_fixed = tk.BooleanVar(value=False) ttk.Checkbutton(top, text="显示固定磁盘\n(读卡器/USB硬盘)", variable=self.var_include_fixed, command=self.refresh_drives).pack(side=tk.RIGHT, padx=(0, 10)) self.btn_refresh = ttk.Button(top, text="刷新列表", command=self.refresh_drives) self.btn_refresh.pack(side=tk.RIGHT) list_frame = ttk.Frame(self.root, padding=(10, 0)) list_frame.pack(fill=tk.BOTH, expand=True) cols = ("盘符", "卷标", "文件系统", "总容量", "可用空间") self.tree = ttk.Treeview(list_frame, columns=cols, show="headings", selectmode="browse", height=6) for c, w in zip(cols, (70, 140, 90, 110, 110)): self.tree.heading(c, text=c) self.tree.column(c, width=w, anchor=tk.CENTER) self.tree.pack(fill=tk.BOTH, expand=True, side=tk.LEFT) sb = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.tree.yview) sb.pack(side=tk.RIGHT, fill=tk.Y) self.tree.configure(yscrollcommand=sb.set) self.tree.bind("<>", self._on_select) mode_frame = ttk.Frame(self.root, padding=10) mode_frame.pack(fill=tk.X) ttk.Label(mode_frame, text="备份模式:", font=("", 9, "bold")).pack(side=tk.LEFT, padx=(0, 10)) self.backup_mode = tk.StringVar(value="full") ttk.Radiobutton(mode_frame, text="全量备份(镜像同步)", variable=self.backup_mode, value="full").pack(side=tk.LEFT, padx=(0, 15)) ttk.Radiobutton(mode_frame, text="增量备份(仅新增/更新)", variable=self.backup_mode, value="incremental").pack(side=tk.LEFT) opt_frame = ttk.Frame(self.root, padding=(10, 0)) opt_frame.pack(fill=tk.X) self.var_verify = tk.BooleanVar(value=True) ttk.Checkbutton(opt_frame, text="复制后 SHA-256 校验(推荐)", variable=self.var_verify).pack(side=tk.LEFT, padx=(0, 12)) self.var_deep = tk.BooleanVar(value=False) ttk.Checkbutton(opt_frame, text="全量校验(重算所有文件哈希)", variable=self.var_deep).pack(side=tk.LEFT, padx=(0, 12)) self.var_hard = tk.BooleanVar(value=False) ttk.Checkbutton(opt_frame, text="彻底删除多余文件(默认移入隔离区)", variable=self.var_hard).pack(side=tk.LEFT) dest_frame = ttk.Frame(self.root, padding=(10, 6)) dest_frame.pack(fill=tk.X) ttk.Label(dest_frame, text="备份到:").pack(side=tk.LEFT) self.dest_var = tk.StringVar(value=BACKUP_ROOT) ttk.Entry(dest_frame, textvariable=self.dest_var, state="readonly").pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5) ttk.Button(dest_frame, text="浏览...", command=self._browse_dest).pack(side=tk.RIGHT) btn_frame = ttk.Frame(self.root, padding=10) btn_frame.pack(fill=tk.X) self.btn_backup = ttk.Button(btn_frame, text="开始备份", command=self.start_backup, state=tk.DISABLED) self.btn_backup.pack(side=tk.LEFT, padx=(0, 10)) self.btn_cancel = ttk.Button(btn_frame, text="取消", command=self.cancel_backup, state=tk.DISABLED) self.btn_cancel.pack(side=tk.LEFT, padx=(0, 10)) ttk.Button(btn_frame, text="打开隔离区", command=self._open_quarantine).pack(side=tk.LEFT) self.status_label = ttk.Label(btn_frame, text="") self.status_label.pack(side=tk.RIGHT) self.progress = ttk.Progressbar(self.root, mode="determinate", maximum=100) self.progress.pack(fill=tk.X, padx=10, pady=(0, 5)) log_frame = ttk.Frame(self.root, padding=(10, 0)) log_frame.pack(fill=tk.BOTH, expand=True) ttk.Label(log_frame, text="日志:", font=("", 9, "bold")).pack(anchor=tk.W) self.log_text = tk.Text(log_frame, height=10, state=tk.DISABLED, wrap=tk.WORD) self.log_text.pack(fill=tk.BOTH, expand=True) lsb = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.log_text.yview) lsb.pack(side=tk.RIGHT, fill=tk.Y) self.log_text.configure(yscrollcommand=lsb.set) # ---------- 磁盘列表 ---------- def refresh_drives(self): self.tree.delete(*self.tree.get_children()) self.selected_drive = None self.btn_backup.config(state=tk.DISABLED) drives = get_usb_drives(self.var_include_fixed.get()) if not drives: self.tree.insert("", tk.END, values=("未检测到U盘", "", "", "", "")) self.log("未检测到可移动磁盘,请插入U盘后点击刷新。") return for d in drives: vol = get_volume_name(d) fs = get_volume_info(d)["fs"] total, free = get_drive_info(d) self.tree.insert("", tk.END, values=(d, vol, fs, _fmt_size(total), _fmt_size(free))) self.log("检测到 %d 个磁盘,请点击选择。" % len(drives)) def _on_select(self, event): sel = self.tree.selection() if not sel: return vals = self.tree.item(sel[0])["values"] letter = str(vals[0]) if len(letter) == 3 and letter[1] == ":": self.selected_drive = letter self.btn_backup.config(state=tk.NORMAL) self.log("已选择: %s (%s)" % (letter, vals[1])) else: self.selected_drive = None self.btn_backup.config(state=tk.DISABLED) def _browse_dest(self): path = filedialog.askdirectory(initialdir=self.dest_var.get() or BACKUP_ROOT) if path: self.dest_var.set(os.path.normpath(path)) self.log("目标路径已更改为: %s" % path) def _open_quarantine(self): q = os.path.join(self.dest_var.get(), QUARANTINE_DIR) if os.path.isdir(_long(q)): os.startfile(_plain(q)) else: messagebox.showinfo("隔离区", "还没有隔离区:\n%s" % q) # ---------- 日志/进度 ---------- def log(self, msg): self.log_text.config(state=tk.NORMAL) self.log_text.insert(tk.END, str(msg) + "\n") self.log_text.see(tk.END) self.log_text.config(state=tk.DISABLED) def update_progress(self, value, status_text): self.root.after(0, lambda: self._update_progress_safe(value, status_text)) def _update_progress_safe(self, value, status_text): self.progress["value"] = value self.status_label.config(text=status_text) # ---------- 备份 ---------- def start_backup(self): if not self.selected_drive: messagebox.showwarning("提示", "请先选择一个U盘") return if not os.path.exists(self.selected_drive): messagebox.showerror("错误", "磁盘 %s 不存在或已拔出!" % self.selected_drive) self.refresh_drives() return self.current_mode = self.backup_mode.get() dest_base = self.dest_var.get() vol = get_volume_name(self.selected_drive) letter = self.selected_drive[0] folder = "%s盘_%s" % (letter, vol if vol else "") dest_path = os.path.join(dest_base, folder) try: _ensure_dir(dest_path) except OSError as e: messagebox.showerror("错误", "无法创建目标目录:\n%s\n%s" % (dest_path, e)) return self.log("=" * 56) self.log("开始%s" % ("全量备份(镜像同步)" if self.current_mode == "full" else "增量备份")) self.log(" 源: %s" % self.selected_drive) self.log(" 目标: %s" % dest_path) self.log("=" * 56) self.progress["value"] = 0 self.status_label.config(text="准备中...") self.btn_backup.config(state=tk.DISABLED) self.btn_cancel.config(state=tk.NORMAL) self.btn_refresh.config(state=tk.DISABLED) self.engine = BackupEngine( source=self.selected_drive, dest=dest_path, mode=self.current_mode, verify=self.var_verify.get(), deep_verify=self.var_deep.get(), hard_delete=self.var_hard.get(), progress_callback=self.update_progress, log_callback=lambda msg: self.root.after(0, self.log, msg)) self.backup_thread = threading.Thread(target=self._run_backup, daemon=True) self.backup_thread.start() def _run_backup(self): try: ok, stats = self.engine.run() err = None except BackupError as e: ok, stats, err = False, None, str(e) except Exception as e: # noqa: BLE001 ok, stats, err = False, None, "%s: %s" % (type(e).__name__, e) self.root.after(0, lambda: self._backup_done(ok, stats, err)) def _backup_done(self, ok, stats, err): self.btn_backup.config(state=tk.NORMAL) self.btn_cancel.config(state=tk.DISABLED) self.btn_refresh.config(state=tk.NORMAL) self.engine = None self.backup_thread = None if err: self.status_label.config(text="失败") self.log("[错误] " + err) messagebox.showerror("备份失败", err) elif ok: self.status_label.config(text="备份完成") else: self.status_label.config(text="未完成(有失败项)") messagebox.showwarning("备份未完成", "存在 %d 项失败,详见日志。" % (stats or {}).get("failed", 0)) def cancel_backup(self): if self.engine: self.engine.cancel() self.log("[取消中] 正在停止备份...") def run(self): self.root.mainloop() if __name__ == "__main__": BackupApp().run()