# -*- 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 json 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.1.0" BACKUP_ROOT_FALLBACK = "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 CONFIG_DIR = os.path.join(os.environ.get("APPDATA") or os.path.expanduser("~"), "UdiskBackup") CONFIG_PATH = os.path.join(CONFIG_DIR, "config.json") INVALID_NAME_CHARS = '\\/:*?"<>|\r\n\t' RESERVED_NAMES = { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", } # 系统目录:无法读取也没意义,直接跳过(全量镜像时也不删除它们) 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, dest=self.dest, failures=list(self.failures), warnings=list(self.warnings), scan_complete=self.scan_complete, message=message) # ==================== 配置 / 目录命名 ==================== def safe_folder_name(label, fallback="无卷标U盘"): """把卷标变成合法的目录名:去掉 Windows 非法字符、首尾空格/点,避开保留名。""" name = (label or "").strip() for ch in INVALID_NAME_CHARS: name = name.replace(ch, "_") name = name.strip(" .") if not name: name = fallback if name.split(".")[0].upper() in RESERVED_NAMES: name = "_" + name return name[:80] def backup_dir_for(base, drive): """返回 (目标目录, 是否沿用了旧版目录)。 新规则:<备份根目录>\\<卷标> —— 不再带盘符; 兼容旧规则:<备份根目录>\\<盘符>盘_<卷标>,旧目录已存在时继续沿用,避免重复整盘拷贝。 """ label = get_volume_name(drive) new_path = os.path.join(base, safe_folder_name(label)) legacy = os.path.join(base, "%s盘_%s" % (drive[0], label)) if not os.path.isdir(_long(new_path)) and os.path.isdir(_long(legacy)): return legacy, True return new_path, False def load_config(path=None): """读取配置(失败一律返回空字典,不打扰用户)。""" p = path or CONFIG_PATH try: with open(p, "r", encoding="utf-8") as f: data = json.load(f) return data if isinstance(data, dict) else {} except (OSError, ValueError): return {} def save_config(cfg, path=None): """原子写入配置(失败静默)。""" p = path or CONFIG_PATH try: d = os.path.dirname(p) if d: os.makedirs(d, exist_ok=True) tmp = p + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=2) os.replace(tmp, p) return True except OSError: return False def default_dest(): """首次运行时的默认备份根目录:可用空间最大的固定盘下的 “U盘备份”。""" best, best_free = None, -1 try: bitmask = ctypes.windll.kernel32.GetLogicalDrives() except (OSError, AttributeError): bitmask = 0 for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": if bitmask & 1: d = "%s:\\" % letter if ctypes.windll.kernel32.GetDriveTypeW(d) == 3: # DRIVE_FIXED try: _total, free = get_drive_info(d) except OSError: continue if free > best_free: best, best_free = d, free bitmask >>= 1 if best: return os.path.join(best, BACKUP_ROOT_FALLBACK) return os.path.join(os.path.expanduser("~"), BACKUP_ROOT_FALLBACK) # ==================== 应用界面 ==================== 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: PAD = 10 def __init__(self): self.cfg = load_config() self.root = tk.Tk() self.root.title("%s v%s" % (APP_NAME, APP_VERSION)) self.root.geometry(self.cfg.get("geometry") or "760x700") self.root.minsize(680, 620) 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._init_style() self._build_ui() self.refresh_drives() self.root.protocol("WM_DELETE_WINDOW", self._on_close) # ---------- 样式 ---------- def _init_style(self): style = ttk.Style(self.root) try: if "vista" in style.theme_names(): style.theme_use("vista") except tk.TclError: pass for name in ("TLabelframe", "TFrame", "TLabel", "TCheckbutton"): style.configure(name, padding=0) style.configure("Card.TLabelframe", padding=10) style.configure("Card.TLabelframe.Label", font=("", 9, "bold")) style.configure("Title.TLabel", font=("", 13, "bold")) style.configure("Hint.TLabel", foreground="#666666") style.configure("Path.TLabel", foreground="#0a5a9e") style.configure("Accent.TButton", font=("", 9, "bold")) style.configure("Treeview", rowheight=24) # ---------- 布局 ---------- def _build_ui(self): outer = ttk.Frame(self.root, padding=(12, 10, 12, 6)) outer.pack(fill=tk.BOTH, expand=True) # 标题栏 head = ttk.Frame(outer) head.pack(fill=tk.X) ttk.Label(head, text=APP_NAME, style="Title.TLabel").pack(side=tk.LEFT) ttk.Label(head, text=" v" + APP_VERSION, style="Hint.TLabel").pack(side=tk.LEFT, padx=(4, 0)) self.btn_refresh = ttk.Button(head, text="刷新磁盘", command=self.refresh_drives) self.btn_refresh.pack(side=tk.RIGHT) self.var_include_fixed = tk.BooleanVar(value=bool(self.cfg.get("include_fixed"))) ttk.Checkbutton(head, text="显示固定磁盘", variable=self.var_include_fixed, command=self.refresh_drives).pack(side=tk.RIGHT, padx=(0, 10)) # 磁盘列表 disk = ttk.LabelFrame(outer, text=" 1. 选择要备份的磁盘 ", style="Card.TLabelframe") disk.pack(fill=tk.BOTH, expand=False, pady=(10, 0)) cols = ("盘符", "卷标", "文件系统", "总容量", "可用空间") self.tree = ttk.Treeview(disk, columns=cols, show="headings", selectmode="browse", height=5) for c, w, anchor in zip(cols, (70, 170, 90, 110, 110), ("center", "w", "center", "center", "center")): self.tree.heading(c, text=c) self.tree.column(c, width=w, anchor=anchor) self.tree.pack(fill=tk.BOTH, expand=True, side=tk.LEFT) sb = ttk.Scrollbar(disk, 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) # 备份设置 opts = ttk.LabelFrame(outer, text=" 2. 备份设置 ", style="Card.TLabelframe") opts.pack(fill=tk.X, pady=(10, 0)) mode_row = ttk.Frame(opts) mode_row.pack(fill=tk.X) ttk.Label(mode_row, text="模式:", width=6).pack(side=tk.LEFT) self.backup_mode = tk.StringVar(value=self.cfg.get("mode") or "full") ttk.Radiobutton(mode_row, text="全量镜像(目标与源一致)", variable=self.backup_mode, value="full").pack(side=tk.LEFT, padx=(0, 18)) ttk.Radiobutton(mode_row, text="增量(只增改,不删)", variable=self.backup_mode, value="incremental").pack(side=tk.LEFT) chk_row = ttk.Frame(opts) chk_row.pack(fill=tk.X, pady=(6, 0)) ttk.Label(chk_row, text="安全:", width=6).pack(side=tk.LEFT) self.var_verify = tk.BooleanVar(value=bool(self.cfg.get("verify", True))) ttk.Checkbutton(chk_row, text="复制后校验 SHA-256", variable=self.var_verify).pack(side=tk.LEFT, padx=(0, 14)) self.var_deep = tk.BooleanVar(value=bool(self.cfg.get("deep_verify", False))) ttk.Checkbutton(chk_row, text="全量校验(重算全部哈希)", variable=self.var_deep).pack(side=tk.LEFT, padx=(0, 14)) self.var_hard = tk.BooleanVar(value=bool(self.cfg.get("hard_delete", False))) ttk.Checkbutton(chk_row, text="彻底删除多余文件", variable=self.var_hard).pack(side=tk.LEFT) # 目标路径 dest_box = ttk.LabelFrame(outer, text=" 3. 备份到 ", style="Card.TLabelframe") dest_box.pack(fill=tk.X, pady=(10, 0)) dest_row = ttk.Frame(dest_box) dest_row.pack(fill=tk.X) self.dest_var = tk.StringVar(value=self._initial_dest()) ttk.Entry(dest_row, textvariable=self.dest_var, state="readonly").pack(side=tk.LEFT, fill=tk.X, expand=True) ttk.Button(dest_row, text="浏览...", command=self._browse_dest).pack(side=tk.RIGHT, padx=(6, 0)) ttk.Button(dest_row, text="打开", width=6, command=self._open_dest).pack(side=tk.RIGHT) self.preview_var = tk.StringVar(value="选择磁盘后显示实际备份目录") ttk.Label(dest_box, textvariable=self.preview_var, style="Path.TLabel").pack( anchor=tk.W, pady=(6, 0)) ttk.Label(dest_box, text="规则:<备份根目录>\\,不再按盘符建子目录", style="Hint.TLabel").pack(anchor=tk.W) # 操作区 actions = ttk.Frame(outer) actions.pack(fill=tk.X, pady=(10, 0)) self.btn_backup = ttk.Button(actions, text="开始备份", style="Accent.TButton", command=self.start_backup, state=tk.DISABLED) self.btn_backup.pack(side=tk.LEFT, ipadx=10) self.btn_cancel = ttk.Button(actions, text="取消", command=self.cancel_backup, state=tk.DISABLED) self.btn_cancel.pack(side=tk.LEFT, padx=(8, 0)) ttk.Button(actions, text="隔离区", command=self._open_quarantine).pack(side=tk.RIGHT) prog_row = ttk.Frame(outer) prog_row.pack(fill=tk.X, pady=(8, 0)) self.progress = ttk.Progressbar(prog_row, mode="determinate", maximum=100) self.progress.pack(side=tk.LEFT, fill=tk.X, expand=True) self.pct_label = ttk.Label(prog_row, text="0%", width=6, anchor=tk.E) self.pct_label.pack(side=tk.RIGHT, padx=(6, 0)) # 日志 log_box = ttk.LabelFrame(outer, text=" 日志 ", style="Card.TLabelframe") log_box.pack(fill=tk.BOTH, expand=True, pady=(10, 0)) self.log_text = tk.Text(log_box, height=10, state=tk.DISABLED, wrap=tk.WORD, font=("Consolas", 9), relief=tk.FLAT, background="#fbfbfb", padx=6, pady=4) self.log_text.pack(fill=tk.BOTH, expand=True, side=tk.LEFT) lsb = ttk.Scrollbar(log_box, orient=tk.VERTICAL, command=self.log_text.yview) lsb.pack(side=tk.RIGHT, fill=tk.Y) self.log_text.configure(yscrollcommand=lsb.set) self.log_text.tag_configure("err", foreground="#c62828") self.log_text.tag_configure("warn", foreground="#b26a00") self.log_text.tag_configure("ok", foreground="#2e7d32") self.log_text.tag_configure("hint", foreground="#777777") # 状态栏 self.status = tk.StringVar(value="就绪") bar = ttk.Frame(self.root, relief=tk.SUNKEN, padding=(10, 4)) bar.pack(fill=tk.X, side=tk.BOTTOM) ttk.Label(bar, textvariable=self.status, anchor=tk.W).pack(side=tk.LEFT) self.status_right = tk.StringVar(value="") ttk.Label(bar, textvariable=self.status_right, style="Hint.TLabel").pack(side=tk.RIGHT) # ---------- 配置 ---------- def _initial_dest(self): saved = self.cfg.get("last_dest") if saved and os.path.isdir(_long(saved)): return saved return default_dest() def _remember(self, **kw): self.cfg.update(kw) self.cfg["include_fixed"] = bool(self.var_include_fixed.get()) self.cfg["mode"] = self.backup_mode.get() self.cfg["verify"] = bool(self.var_verify.get()) self.cfg["deep_verify"] = bool(self.var_deep.get()) self.cfg["hard_delete"] = bool(self.var_hard.get()) save_config(self.cfg) def _on_close(self): try: self.cfg["geometry"] = self.root.winfo_geometry() save_config(self.cfg) finally: self.root.destroy() # ---------- 磁盘列表 ---------- 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=("未检测到磁盘", "", "", "", "")) self.log("未检测到可移动磁盘,请插入U盘后点击“刷新磁盘”。", "warn") self.preview_var.set("未检测到磁盘") return for d in drives: vol = get_volume_name(d) info = get_volume_info(d) total, free = get_drive_info(d) self.tree.insert("", tk.END, values=(d, vol, info["fs"], _fmt_size(total), _fmt_size(free))) self.log("检测到 %d 个磁盘,请点击选择。" % len(drives), "hint") self.status.set("就绪") 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._update_preview() self.log("已选择: %s (%s)" % (letter, vals[1])) self.status.set("已选择 %s,可以开始备份" % letter) else: self.selected_drive = None self.btn_backup.config(state=tk.DISABLED) def _update_preview(self): if not self.selected_drive: self.preview_var.set("选择磁盘后显示实际备份目录") return path, legacy = backup_dir_for(self.dest_var.get(), self.selected_drive) self.preview_var.set(path + (" (沿用旧版目录)" if legacy else "")) self.status_right.set("目标: " + path) def _browse_dest(self): path = filedialog.askdirectory(initialdir=self.dest_var.get() or default_dest()) if path: self.dest_var.set(os.path.normpath(path)) self._remember(last_dest=self.dest_var.get()) self._update_preview() self.log("备份根目录已改为: %s" % path) def _open_dest(self): p = self.dest_var.get() if os.path.isdir(_long(p)): os.startfile(_plain(p)) else: messagebox.showinfo("提示", "目录还不存在:\n%s" % p) 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, tag=None): text = str(msg) if tag is None: if "[失败]" in text or "[错误]" in text or "失败" in text: tag = "err" elif "[警告]" in text or "警告" in text: tag = "warn" elif text.startswith("[完成]"): tag = "ok" self.log_text.config(state=tk.NORMAL) self.log_text.insert(tk.END, text + "\n", tag or ()) 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.pct_label.config(text="%d%%" % int(value)) self.status.set(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() dest_path, legacy = backup_dir_for(dest_base, self.selected_drive) try: _ensure_dir(dest_path) except OSError as e: messagebox.showerror("错误", "无法创建目标目录:\n%s\n%s" % (dest_path, e)) return self._remember(last_dest=dest_base) self.log("=" * 58, "hint") self.log("开始%s" % ("全量备份(镜像同步)" if self.current_mode == "full" else "增量备份")) self.log(" 源: %s" % self.selected_drive) self.log(" 目标: %s%s" % (dest_path, " [沿用旧版目录]" if legacy else "")) self.log("=" * 58, "hint") self.progress["value"] = 0 self.pct_label.config(text="0%") self.status.set("准备中...") 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.set("失败") self.log("[错误] " + err, "err") messagebox.showerror("备份失败", err) elif ok: self.status.set("备份完成") self.status_right.set("目标: " + (stats or {}).get("dest", "")) self.pct_label.config(text="100%") else: self.status.set("未完成(有失败项)") messagebox.showwarning("备份未完成", "存在 %d 项失败,详见日志。" % (stats or {}).get("failed", 0)) def cancel_backup(self): if self.engine: self.engine.cancel() self.log("[取消中] 正在停止备份...", "warn") def run(self): self.root.mainloop() if __name__ == "__main__": BackupApp().run()