netparse-cmdb 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
netparse/cli/parse.py ADDED
@@ -0,0 +1,216 @@
1
+ """parse / lint 子命令实现。
2
+
3
+ 这两个子命令纯靠引擎,不需要生产脚本,也不碰只读语料 —— 是库最先要能跑起来的部分。
4
+ """
5
+
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ from .. import engine
11
+ from .. import masking
12
+
13
+
14
+ def parse_file(template, config, mask_value=None, heuristic=True):
15
+ """解析一个配置文件,返回 (集合树, 结果字典)。
16
+
17
+ 库用法入口:不想走命令行时直接调这个。
18
+ """
19
+ if mask_value is not None:
20
+ masking.CONFIG.value = mask_value
21
+ masking.CONFIG.heuristic = heuristic
22
+
23
+ colls = engine.parse_template(template)
24
+ with open(config, encoding="utf-8", errors="replace") as f:
25
+ lines = f.readlines()
26
+ return colls, engine.run(colls, lines)
27
+
28
+
29
+ def _print_lint(issues, as_json):
30
+ if as_json:
31
+ print(json.dumps([{"level": lv, "collection": c, "message": m} for lv, c, m in issues],
32
+ ensure_ascii=False, indent=2))
33
+ return
34
+ print("=== lint ===")
35
+ for lv, coll, msg in issues:
36
+ print(" [%s] %s: %s" % (lv, coll, msg))
37
+
38
+
39
+ def _parse_fields(spec):
40
+ """解析 --fields 字符串 → run() 的 fields dict 形态。
41
+
42
+ 例:Interfaces=Name,Type,IpAddress;RouteStatics=Prefix,Mask,NextHop
43
+ 集合名不带 = → None(保留全部字段)
44
+ """
45
+ if not spec:
46
+ return None
47
+ out = {}
48
+ for part in spec.split(";"):
49
+ part = part.strip()
50
+ if not part:
51
+ continue
52
+ cname, _, flds = part.partition("=")
53
+ cname = cname.strip()
54
+ if flds.strip():
55
+ out[cname] = {x.strip() for x in flds.split(",") if x.strip()}
56
+ else:
57
+ out[cname] = None
58
+ return out or None
59
+
60
+
61
+ def _collect_config_files(config):
62
+ """config 参数展开:文件 → [自身];文件夹 → 递归全部文件(按路径排序)。"""
63
+ if os.path.isfile(config):
64
+ return [config], False
65
+ if os.path.isdir(config):
66
+ root = os.path.abspath(config)
67
+ files = []
68
+ for dirpath, _dirnames, filenames in os.walk(root):
69
+ for fn in sorted(filenames):
70
+ files.append(os.path.join(dirpath, fn))
71
+ files.sort()
72
+ if not files:
73
+ raise SystemExit("错误:文件夹里没有任何文件:%s" % config)
74
+ return files, True
75
+ raise SystemExit("错误:配置路径不存在:%s" % config)
76
+
77
+
78
+ def main(args):
79
+ """`netparse parse <模板> <配置文件|配置文件夹> [输出路径]`"""
80
+ if args.mask_value is not None:
81
+ masking.CONFIG.value = args.mask_value
82
+ if args.no_mask_heuristic:
83
+ masking.CONFIG.heuristic = False
84
+
85
+ # 解释器模式透传:--selftest 时段内 cfg=剩余配置路径、argv=剩余参数
86
+ main_cfg = args.config if getattr(args, "selftest", False) and args.config else None
87
+ main_argv = []
88
+ if getattr(args, "selftest", False):
89
+ rest = [a for a in (sys.argv[1:] or []) if a not in ("-m",)]
90
+ # 取模板之后的参数(剔除已知 flag 开头的)
91
+ i = rest.index(args.template) + 1 if args.template in rest else len(rest)
92
+ main_argv = [a for a in rest[i:] if not a.startswith("-") and a != "--json" and a != "--selftest"]
93
+ colls = engine.parse_template(args.template, main_cfg=main_cfg, main_argv=main_argv) # [__main__] 段在此执行
94
+
95
+ # ── --selftest:只加载模板并执行 [__main__] 段,成功即 PASS ──
96
+ if getattr(args, "selftest", False):
97
+ if args.config:
98
+ sys.stderr.write("[netparse] --selftest 忽略 config 参数: %s\n"
99
+ % args.config)
100
+ issues = engine.lint(colls)
101
+ errs = [x for x in issues if x[0] == "错误"]
102
+ for lv, coll, msg in issues:
103
+ sys.stderr.write(" [%s] %s: %s\n" % (lv, coll, msg))
104
+ if errs:
105
+ print("[FAIL] 模板加载/自测试失败(见上方错误,共 %d 条)" % len(errs))
106
+ return 1
107
+ print("[PASS] %s: [__main__] 自测试通过" % os.path.basename(args.template))
108
+ return 0
109
+
110
+ if not args.config:
111
+ sys.stderr.write("netparse parse: 缺少 config 参数"
112
+ "(只加载/自测模板请加 --selftest)\n")
113
+ return 2
114
+
115
+ # lint 是诊断信息:--json / 输出文件时走 stderr,保证 stdout / 文件是纯 JSON
116
+ # (否则 `netparse parse ... --json > out.json` 出来的文件无法 json.load)
117
+ issues = engine.lint(colls)
118
+ if issues:
119
+ report = ["=== lint ==="]
120
+ report += [" [%s] %s: %s" % (lv, coll, msg) for lv, coll, msg in issues]
121
+ report.append("")
122
+ stream = sys.stderr if (args.json or args.output) else sys.stdout
123
+ stream.write("\n".join(report) + "\n")
124
+
125
+ files, is_batch = _collect_config_files(args.config)
126
+
127
+ # ── 批量模式:config 是文件夹 → 每个文件一个同名 .json,写入输出目录 ──
128
+ if is_batch:
129
+ out_dir = args.output
130
+ if not out_dir:
131
+ raise SystemExit("错误:config 是文件夹时必须指定输出目录(第三个参数)")
132
+ os.makedirs(out_dir, exist_ok=True)
133
+ root = os.path.abspath(args.config)
134
+ failures = []
135
+ for fp in files:
136
+ rel = os.path.relpath(fp, root)
137
+ try:
138
+ with open(fp, encoding="utf-8", errors="replace") as f:
139
+ lines = f.readlines()
140
+ res = engine.run(colls, lines,
141
+ fields=_parse_fields(getattr(args, "fields", None)))
142
+ # 相对路径映射到输出目录(保留子目录结构),扩展名换成 .json
143
+ out_file = os.path.join(out_dir, os.path.splitext(rel)[0] + ".json")
144
+ os.makedirs(os.path.dirname(os.path.abspath(out_file)), exist_ok=True)
145
+ with open(out_file, "w", encoding="utf-8") as fh:
146
+ json.dump(res, fh, ensure_ascii=False, indent=2)
147
+ except Exception as e:
148
+ failures.append({"file": rel, "error": str(e)})
149
+ sys.stderr.write("[fail] %s: %s\n" % (rel, e))
150
+ sys.stderr.write("[mask] L1=%d L2=%d mask=%r heuristic=%s\n"
151
+ % (masking.STATS.l1_hits, masking.STATS.l2_hits,
152
+ masking.CONFIG.value, masking.CONFIG.heuristic))
153
+ ok = len(files) - len(failures)
154
+ print("批量解析完成:%d 文件 / 成功 %d / 失败 %d → %s"
155
+ % (len(files), ok, len(failures), os.path.abspath(out_dir)))
156
+ if failures:
157
+ for f in failures:
158
+ print(" 失败: %s (%s)" % (f["file"], f["error"]))
159
+ return 0 if not failures else 1
160
+
161
+ # ── 单文件模式 ──
162
+ with open(args.config, encoding="utf-8", errors="replace") as f:
163
+ lines = f.readlines()
164
+ res = engine.run(colls, lines, fields=_parse_fields(getattr(args, "fields", None)))
165
+
166
+ # 脱敏统计写 stderr:stdout 留给 JSON / 文本输出,不污染
167
+ sys.stderr.write("[mask] L1=%d L2=%d mask=%r heuristic=%s\n"
168
+ % (masking.STATS.l1_hits, masking.STATS.l2_hits,
169
+ masking.CONFIG.value, masking.CONFIG.heuristic))
170
+
171
+ if args.output:
172
+ os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
173
+ with open(args.output, "w", encoding="utf-8") as fh:
174
+ json.dump(res, fh, ensure_ascii=False, indent=2)
175
+ print("解析完成 → %s" % args.output)
176
+ return 0
177
+
178
+ if args.json:
179
+ print(json.dumps(res, ensure_ascii=False, indent=2))
180
+ return 0
181
+
182
+ print("集合树:")
183
+ for c in colls:
184
+ pad = " " * c.indent
185
+ key = ("Key=" + ",".join(c.key_fields)) if c.key_fields else ""
186
+ print("%s%-22s type=%-6s start=%-22r fields=%d rules=%d %s"
187
+ % (pad, c.name, c.type, c.start, len(c.all_fields), len(c.rules), key))
188
+
189
+ print("\n=== 结果 ===")
190
+ for k, arr in res.items():
191
+ print(" %-22s %5d 条" % (k, len(arr)))
192
+
193
+ for k in ("Interfaces", "IpAddress"):
194
+ if res.get(k):
195
+ print("\n=== %s 前 2 条 ===" % k)
196
+ for it in res[k][:2]:
197
+ print(" " + json.dumps(it, ensure_ascii=False)[:300])
198
+ return 0
199
+
200
+
201
+ def main_lint(args):
202
+ """`netparse lint <模板>`"""
203
+ colls = engine.parse_template(args.template)
204
+ issues = engine.lint(colls)
205
+ _print_lint(issues, args.json)
206
+
207
+ errors = [i for i in issues if i[0] == "错误"]
208
+ warnings = [i for i in issues if i[0] == "警告"]
209
+ if not args.json:
210
+ print("\n%d 个错误 / %d 个警告" % (len(errors), len(warnings)))
211
+
212
+ if errors:
213
+ return 1
214
+ if args.strict and warnings:
215
+ return 1
216
+ return 0
@@ -0,0 +1,158 @@
1
+ import argparse
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import sys
6
+ import time
7
+
8
+ from ..paths import change_dir
9
+
10
+ DEFAULT_BASELINE = os.path.join(change_dir(), "readonly-baseline.json")
11
+
12
+ # 只读根目录:(候选路径列表, 是否算 sha1)
13
+ # ⚠️ 规格里写的是 `E:\配置文件\原始配置\`,实测不存在,
14
+ # 真实路径是 `E:\配置文件\BRAS&SR\原始配置\`(26 个月目录 / 10054 个文件 / 3.3GB)。
15
+ # 两个候选都留着,谁存在用谁 —— 记录进基线,事后可核对。
16
+ ROOTS = [
17
+ ([r"E:\配置文件\BRAS&SR\原始配置", r"E:\配置文件\原始配置"], True),
18
+ ([r"E:\配置文件\BRAS&SR\解析后"], False),
19
+ ([r"E:\配置文件\配置解析\华为"], False),
20
+ ]
21
+
22
+ CHUNK = 1024 * 1024
23
+
24
+
25
+ def sha1_of(path):
26
+ h = hashlib.sha1()
27
+ with open(path, "rb") as f:
28
+ while True:
29
+ b = f.read(CHUNK)
30
+ if not b:
31
+ break
32
+ h.update(b)
33
+ return h.hexdigest()
34
+
35
+
36
+ def pick_root(candidates):
37
+ for c in candidates:
38
+ if os.path.isdir(c):
39
+ return c
40
+ return None
41
+
42
+
43
+ def snapshot(root, with_sha1):
44
+ """遍历 root,返回 {相对路径: [size, mtime_ns, sha1或None]}"""
45
+ out = {}
46
+ base = os.path.abspath(root)
47
+ for dp, _dn, fn in os.walk(base):
48
+ for f in fn:
49
+ p = os.path.join(dp, f)
50
+ rel = os.path.relpath(p, base).replace(os.sep, "/")
51
+ try:
52
+ st = os.stat(p)
53
+ except OSError:
54
+ continue
55
+ digest = None
56
+ if with_sha1:
57
+ try:
58
+ digest = sha1_of(p)
59
+ except OSError:
60
+ digest = None
61
+ out[rel] = [st.st_size, st.st_mtime_ns, digest]
62
+ return out
63
+
64
+
65
+ def capture(baseline_path):
66
+ roots_out = []
67
+ for candidates, with_sha1 in ROOTS:
68
+ root = pick_root(candidates)
69
+ if root is None:
70
+ roots_out.append({"candidates": candidates, "exists": False,
71
+ "sha1": with_sha1, "files": {}})
72
+ print(f" [缺失] {candidates[0]}")
73
+ continue
74
+ t0 = time.time()
75
+ snap = snapshot(root, with_sha1)
76
+ roots_out.append({"candidates": candidates, "path": root, "exists": True,
77
+ "sha1": with_sha1, "files": snap})
78
+ print(f" {root}: {len(snap)} 个文件"
79
+ f"({'size+mtime_ns+sha1' if with_sha1 else 'size+mtime_ns'})"
80
+ f" {time.time() - t0:.1f}s")
81
+ data = {
82
+ "captured_at": time.strftime("%Y-%m-%d %H:%M:%S"),
83
+ "roots": roots_out,
84
+ }
85
+ os.makedirs(os.path.dirname(baseline_path), exist_ok=True)
86
+ with open(baseline_path, "w", encoding="utf-8") as f:
87
+ json.dump(data, f, ensure_ascii=False, indent=1)
88
+ total = sum(len(r["files"]) for r in roots_out)
89
+ print(f"基线已写入: {baseline_path}({total} 个文件条目)")
90
+ return 0
91
+
92
+
93
+ def verify(baseline_path, only_root=None):
94
+ if not os.path.isfile(baseline_path):
95
+ print(f"基线不存在: {baseline_path}(先跑 --capture)")
96
+ return 1
97
+ with open(baseline_path, encoding="utf-8") as f:
98
+ data = json.load(f)
99
+
100
+ problems = []
101
+ for r in data["roots"]:
102
+ root = r.get("path")
103
+ if only_root and root and only_root.lower() not in root.lower():
104
+ continue
105
+ if not r.get("exists") or not root or not os.path.isdir(root):
106
+ problems.append(f"根目录不存在或未采集: {r.get('candidates')}")
107
+ continue
108
+ cur = snapshot(root, r.get("sha1", False))
109
+ base = r["files"]
110
+ for rel, meta in base.items():
111
+ if rel not in cur:
112
+ problems.append(f"文件消失: {root}\\{rel}")
113
+ continue
114
+ c = cur[rel]
115
+ if c[0] != meta[0]:
116
+ problems.append(f"size 变化: {root}\\{rel} {meta[0]} -> {c[0]}")
117
+ if c[1] != meta[1]:
118
+ problems.append(f"mtime 变化: {root}\\{rel}")
119
+ if meta[2] and c[2] and meta[2] != c[2]:
120
+ problems.append(f"sha1 变化: {root}\\{rel}")
121
+ for rel in cur:
122
+ if rel not in base:
123
+ problems.append(f"新增文件: {root}\\{rel}")
124
+
125
+ if problems:
126
+ print(f"READ-ONLY 校验失败,共 {len(problems)} 处差异:")
127
+ for p in problems[:40]:
128
+ print(" -", p)
129
+ if len(problems) > 40:
130
+ print(f" ...(另有 {len(problems) - 40} 处)")
131
+ return 1
132
+ print("READ-ONLY OK")
133
+ return 0
134
+
135
+
136
+ def add_arguments(parser):
137
+ parser.add_argument("--capture", action="store_true", help="采集基线")
138
+ parser.add_argument("--verify", action="store_true", help="与基线比对")
139
+ parser.add_argument("--baseline", default=DEFAULT_BASELINE, help="基线文件路径")
140
+ parser.add_argument("--root", default=None, help="--verify 时只查这一个根")
141
+ return parser
142
+
143
+
144
+ def main(args=None):
145
+ if args is None: # 允许 `python -m netparse.cli.readonly` 直跑
146
+ args = add_arguments(argparse.ArgumentParser()).parse_args()
147
+
148
+ if args.capture:
149
+ return capture(args.baseline)
150
+ if args.verify:
151
+ return verify(args.baseline, args.root)
152
+ print("请给出 --capture 或 --verify", file=sys.stderr)
153
+ return 1
154
+
155
+
156
+ if __name__ == "__main__":
157
+ from . import main as _cli_main
158
+ sys.exit(_cli_main(["readonly"] + sys.argv[1:]))
@@ -0,0 +1,255 @@
1
+ """静态路由多形态校验(tasks.md 2.2b.3 / 2.2b.4 / 2.2b.5)。
2
+
3
+ 可重跑的只读校验脚本,回答三个问题:
4
+
5
+ ① 边界形态(2.2b.4):7 种输入形态,netparse 的取值是否与 incumbent 的判据一致
6
+ ② 逐字段一致(2.2b.3):真实文件上 (dest, mask, interface, nexthop, vpn)
7
+ 集合是否与 incumbent 落盘产物**完全相同**
8
+ ③ 丢失率复测(2.2b.5):带**显式出接口**的路由,修前丢多少、修后丢多少
9
+
10
+ ⚠️ 判定"带显式出接口"时**必须排除 NULL0**(`interface NULL0` 在 60/60 个文件里存在;
11
+ 不排除会把分母从 76 污染到 930、丢失率从 94.7% 算成 5.6%)
12
+
13
+ 用法::
14
+
15
+ netparse route-forms # 边界形态 + 60 文件丢失率
16
+ netparse route-forms --sample 120 # 扩大样本
17
+ netparse route-forms --file "<真实配置>" # 单文件逐字段比对
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import re
24
+ import sys
25
+
26
+ from .. import engine
27
+ from ..paths import baseline_template, default_template
28
+
29
+ CUR_TPL = default_template()
30
+ BASE_TPL = baseline_template()
31
+ RAW_ROOT = "E:////配置文件////BRAS&SR////原始配置"
32
+ PARSED_ROOT = "E:////配置文件////BRAS&SR////解析后"
33
+
34
+ # incumbent 的判据(parse_huawei_vrp.py:509-537):首 token 不是 IP、也不是 NULL0 → 出接口
35
+ _IPV4_RE = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}$")
36
+ def looks_like_ip(tok):
37
+ return ":" in tok or bool(_IPV4_RE.match(tok))
38
+
39
+
40
+ def split_iface_nexthop(tokens):
41
+ """incumbent 的判据复刻(只读参考实现,不改 incumbent)。"""
42
+ if not tokens:
43
+ return "", ""
44
+ head = tokens[0]
45
+ if not looks_like_ip(head) and head.upper() != "NULL0":
46
+ return head, (tokens[1] if len(tokens) > 1 else "")
47
+ return "", head
48
+
49
+
50
+ def config_routes(cfg_path):
51
+ """从配置原文按 incumbent 的判据算出 (dest, mask, iface, nexthop, vpn) 列表。"""
52
+ out = []
53
+ for line in open(cfg_path, encoding="utf-8", errors="replace"):
54
+ if not line.startswith("ip route-static "):
55
+ continue
56
+ tokens = line.split()[2:]
57
+ vpn = ""
58
+ if tokens and tokens[0] == "vpn-instance":
59
+ vpn = tokens[1]
60
+ tokens = tokens[2:]
61
+ if len(tokens) < 3:
62
+ continue
63
+ iface, nexthop = split_iface_nexthop(tokens[2:])
64
+ out.append((tokens[0], tokens[1], iface, nexthop, vpn))
65
+ return out
66
+
67
+
68
+ def np_routes(tpl_path, cfg_path):
69
+ """netparse 解析出的 (dest, mask, iface, nexthop, vpn) 集合。"""
70
+ colls = engine.parse_template(tpl_path)
71
+ lines = open(cfg_path, encoding="utf-8", errors="replace").readlines()
72
+ res = engine.run(colls, lines)
73
+ out = set()
74
+ for r in res.get("RouteStatics", []) or []:
75
+ out.add((r.get("Prefix", ""), r.get("Mask", ""),
76
+ r.get("NextHopIface", ""), r.get("NextHop", ""),
77
+ r.get("VpnInstance", "")))
78
+ return out
79
+
80
+
81
+ def incumbent_routes(json_path):
82
+ j = json.load(open(json_path, encoding="utf-8"))
83
+ out = set()
84
+ for r in (j.get("route-static") or {}).get("IPV4") or []:
85
+ out.add((r.get("dest", ""), r.get("mask", ""),
86
+ r.get("interface", ""), r.get("nexthop", ""),
87
+ r.get("vpn", "")))
88
+ return out
89
+
90
+
91
+ # ── ① 边界形态(2.2b.4)──────────────────────────────────
92
+ BOUNDARY = [
93
+ # (配置行, 期望 (NextHop, NextHopIface, VpnInstance, Description))
94
+ ("ip route-static 10.0.0.0 255.0.0.0 10.1.1.1 description pure",
95
+ ("10.1.1.1", "", "", "pure")),
96
+ ("ip route-static 10.0.0.1 255.0.0.0 NULL0",
97
+ ("NULL0", "", "", "")),
98
+ ("ip route-static 10.0.0.2 255.0.0.0 Eth-Trunk188 192.168.0.70 description both",
99
+ ("192.168.0.70", "Eth-Trunk188", "", "both")),
100
+ ("ip route-static 10.0.0.3 255.0.0.0 Eth-Trunk99",
101
+ ("", "Eth-Trunk99", "", "")),
102
+ ("ip route-static 10.0.0.4 255.0.0.0 1.2.3.4 5.6.7.8",
103
+ ("1.2.3.4", "", "", "")),
104
+ ("ip route-static vpn-instance V1 10.0.0.5 255.0.0.0 Eth-Trunk77 172.16.0.1",
105
+ ("172.16.0.1", "Eth-Trunk77", "V1", "")),
106
+ ("ip route-static vpn-instance V2 10.0.0.6 255.0.0.0 10.7.7.7",
107
+ ("10.7.7.7", "", "V2", "")),
108
+ ]
109
+
110
+
111
+ def check_boundary():
112
+ print("=== ① 边界形态(7 种,incumbent 判据 = 首 token 非 IP 且非 NULL0 → 出接口)===")
113
+ cfg = "\n".join(line for line, _ in BOUNDARY) + "\n"
114
+ tmp = os.path.join(HERE, "_boundary_tmp.cfg")
115
+ with open(tmp, "w", encoding="utf-8") as f:
116
+ f.write(cfg)
117
+ try:
118
+ colls = engine.parse_template(CUR_TPL)
119
+ res = engine.run(colls, open(tmp, encoding="utf-8").readlines())
120
+ got = {r.get("Prefix"): r for r in res.get("RouteStatics", []) or []}
121
+ ok = True
122
+ for line, (nh, nhif, vpn, desc) in BOUNDARY:
123
+ toks = line.split()
124
+ prefix = toks[4] if toks[2] == "vpn-instance" else toks[2]
125
+ r = got.get(prefix)
126
+ if r is None:
127
+ print(f" ❌ {line}\n → 没抓到这条路由")
128
+ ok = False
129
+ continue
130
+ actual = (r.get("NextHop", ""), r.get("NextHopIface", ""),
131
+ r.get("VpnInstance", ""), r.get("Description", ""))
132
+ if actual == (nh, nhif, vpn, desc):
133
+ print(f" ✅ {line}\n → NextHop={actual[0]!r} NextHopIface={actual[1]!r} "
134
+ f"VpnInstance={actual[2]!r} Description={actual[3]!r}")
135
+ else:
136
+ print(f" ❌ {line}\n → 实际 {actual} != 期望 {(nh, nhif, vpn, desc)}")
137
+ ok = False
138
+ return ok
139
+ finally:
140
+ os.unlink(tmp)
141
+
142
+
143
+ # ── ② ③ 真实文件校验 ────────────────────────────────────
144
+ def find_pairs(month="cfgfile_20250824"):
145
+ """(原始配置, incumbent JSON) 对。"""
146
+ raw_dir = os.path.join(RAW_ROOT, month, "华为")
147
+ inc_dir = os.path.join(PARSED_ROOT, month, "华为")
148
+ pairs = []
149
+ for f in sorted(os.listdir(inc_dir)):
150
+ if not f.endswith(".json"):
151
+ continue
152
+ stem = f[:-5]
153
+ raw = os.path.join(raw_dir, stem)
154
+ if not os.path.exists(raw):
155
+ raw = os.path.join(raw_dir, stem + ".txt")
156
+ if not os.path.exists(raw):
157
+ continue
158
+ pairs.append((raw, os.path.join(inc_dir, f)))
159
+ return pairs
160
+
161
+
162
+ def check_real(sample, month="cfgfile_20250824"):
163
+ pairs = find_pairs(month)[:sample]
164
+ print(f"=== ②③ 真实文件校验({len(pairs)} 个文件,{month})===")
165
+ exact = 0; mismatch = []
166
+ inc_iface_total = 0; before_iface = 0; after_iface = 0
167
+ lost_examples = []
168
+ for raw, inc in pairs:
169
+ i_set = incumbent_routes(inc)
170
+ a_set = np_routes(CUR_TPL, raw)
171
+ b_set = np_routes(BASE_TPL, raw)
172
+ if i_set == a_set:
173
+ exact += 1
174
+ else:
175
+ only_i = i_set - a_set
176
+ only_a = a_set - i_set
177
+ mismatch.append((os.path.basename(raw), len(only_i), len(only_a),
178
+ list(only_i)[:2], list(only_a)[:2]))
179
+ # 带显式出接口的路由(排除 NULL0)
180
+ inc_iface = {(d, m, i) for (d, m, i, _n, _v) in i_set if i and i.upper() != "NULL0"}
181
+ inc_iface_total += len(inc_iface)
182
+ after_iface += len({(d, m, i) for (d, m, i, _n, _v) in a_set if i and i.upper() != "NULL0"})
183
+ before_iface += len({(d, m, i) for (d, m, i, _n, _v) in b_set if i and i.upper() != "NULL0"})
184
+ lost = inc_iface - {(d, m, i) for (d, m, i, _n, _v) in a_set if i and i.upper() != "NULL0"}
185
+ if lost and len(lost_examples) < 3:
186
+ lost_examples.append((os.path.basename(raw), list(lost)[:2]))
187
+
188
+ print(f" 逐字段集合完全一致的文件: {exact}/{len(pairs)}")
189
+ if mismatch:
190
+ print(f" ⚠️ 不一致文件(前 5 个):")
191
+ for m in mismatch[:5]:
192
+ print(f" {m[0]}: 仅 incumbent 有 {m[1]} 条 / 仅 netparse 有 {m[2]} 条")
193
+ print(f" 仅inc: {m[3]}")
194
+ print(f" 仅net: {m[4]}")
195
+ print(f" 带显式出接口的路由(排除 NULL0):incumbent {inc_iface_total} 条")
196
+ print(f" 修前 netparse 抓到 {before_iface} 条 → 丢 {inc_iface_total - before_iface} 条 "
197
+ f"({100.0 * (inc_iface_total - before_iface) / max(1, inc_iface_total):.1f}%)")
198
+ print(f" 修后 netparse 抓到 {after_iface} 条 → 丢 {inc_iface_total - after_iface} 条 "
199
+ f"({100.0 * (inc_iface_total - after_iface) / max(1, inc_iface_total):.1f}%)")
200
+ if lost_examples:
201
+ print(f" 修后仍丢的样例: {lost_examples}")
202
+ return exact == len(pairs), inc_iface_total, before_iface, after_iface
203
+
204
+
205
+ def add_arguments(parser):
206
+ parser.add_argument("--sample", type=int, default=60, help="真实文件样本数(默认 60)")
207
+ parser.add_argument("--month", default="cfgfile_20250824")
208
+ parser.add_argument("--file", help="单文件逐字段比对(给真实配置路径)")
209
+ return parser
210
+
211
+
212
+ def main(args):
213
+ if args.file:
214
+ return single_file(args.file)
215
+
216
+ ok = check_boundary()
217
+ print()
218
+ exact, total, before, after = check_real(args.sample, args.month)
219
+ print()
220
+ print("RESULT:", "PASS" if (ok and exact) else "FAIL")
221
+ return 0 if (ok and exact) else 1
222
+
223
+
224
+ def single_file(raw):
225
+ """单文件逐字段比对:配置原文 vs 修前/修后模板。
226
+
227
+ 这个分支原脚本在 docstring 里写了 `--file` 但**根本没实现**,参数被 argparse 拒掉。
228
+ 现在补上:直接对真实配置跑两侧模板,把 (dest, mask, iface, nexthop, vpn) 集合打出来,
229
+ 并带 incumbent 判据算出的期望集合 —— 差异一眼可见。
230
+ """
231
+ if not os.path.isfile(raw):
232
+ print("文件不存在:%s" % raw, file=sys.stderr)
233
+ return 2
234
+ expected = config_routes(raw)
235
+ after = np_routes(CUR_TPL, raw)
236
+ before = np_routes(BASE_TPL, raw)
237
+
238
+ print("=== 单文件逐字段比对 ===")
239
+ print("文件:%s" % raw)
240
+ print("incumbent 判据期望:%d 条" % len(expected))
241
+ print("修后模板: %d 条" % len(after))
242
+ print("修前模板: %d 条" % len(before))
243
+ print()
244
+ print("修后 == 期望:%s" % ("是" if after == set(expected) else "否"))
245
+ if after != set(expected):
246
+ only_e = set(expected) - after
247
+ only_a = after - set(expected)
248
+ print(" 期望有而修后无(%d):%r" % (len(only_e), sorted(only_e)[:5]))
249
+ print(" 修后有而期望无(%d):%r" % (len(only_a), sorted(only_a)[:5]))
250
+ return 0 if after == set(expected) else 1
251
+
252
+
253
+ if __name__ == "__main__": # python -m netparse.cli.route_forms 直跑
254
+ from . import main as _cli_main
255
+ sys.exit(_cli_main(["route-forms"] + sys.argv[1:]))