#!/usr/bin/env python3 # -*- coding: utf-8 -*- """客户侧自查脚本(无需安装任何依赖)。 用法: python verify.py 输出: 逐项 PASS/FAIL,最后一行 VERDICT=PASS 或 VERDICT=FAIL 校验内容: 1. 每个 CSV 的 SHA256 与 manifest.json 记录是否一致(文件未被改动); 2. 由各文件哈希重算的 combined_sha256 是否与记录一致; 3. 每张表的行数; 4. 每个外键列的孤儿行数量。 """ import csv, hashlib, json, os, sys HERE = os.path.dirname(os.path.abspath(__file__)) def sha_file(p): h = hashlib.sha256() with open(p, "rb") as f: for c in iter(lambda: f.read(1 << 20), b""): h.update(c) return h.hexdigest() def main(): mf = os.path.join(HERE, "manifest.json") if not os.path.exists(mf): print("FAIL 缺少 manifest.json"); print("VERDICT=FAIL"); return 1 m = json.load(open(mf, encoding="utf-8")) ok = True bad = [] actual = {} for f in m["files"]: p = os.path.join(HERE, f["name"]) if not os.path.exists(p): bad.append(f["name"] + "(缺失)"); actual[f["name"]] = "MISSING"; continue h = sha_file(p) actual[f["name"]] = h if h != f["sha256"]: bad.append(f["name"] + "(哈希不符)") if bad: ok = False print("FAIL 文件校验:" + ", ".join(bad)) else: print("PASS 文件哈希 %d 个全部一致" % len(m["files"])) # 用"实际重算的哈希"再算一遍组合哈希,而不是照抄 manifest 里的值 combined = hashlib.sha256( "".join("%s:%s\n" % (k, actual[k]) for k in sorted(actual)).encode() ).hexdigest() if combined == m["checks"]["combined_sha256"]: print("PASS combined_sha256 " + combined[:16] + "...") else: ok = False print("FAIL combined_sha256 重算与记录不符(记录 %s / 实际 %s)" % (m["checks"]["combined_sha256"][:16], combined[:16])) for tbl, n in m["checks"]["row_counts"].items(): p = os.path.join(HERE, tbl + ".csv") real = sum(1 for _ in open(p, encoding="utf-8-sig")) - 1 if real == n: print("PASS %s 行数 %d" % (tbl, real)) else: ok = False print("FAIL %s 行数 期望 %d 实际 %d" % (tbl, n, real)) for key, v in m["checks"]["fk_orphans"].items(): if v["orphans"] == 0: print("PASS 外键 %s 孤儿 0/%d" % (key, v["checked"])) else: ok = False print("FAIL 外键 %s 孤儿 %d/%d" % (key, v["orphans"], v["checked"])) print("VERDICT=" + ("PASS" if ok else "FAIL")) return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())