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/__init__.py +96 -0
- netparse/__main__.py +8 -0
- netparse/adapters/__init__.py +1 -0
- netparse/adapters/incumbent.py +299 -0
- netparse/cli/__init__.py +148 -0
- netparse/cli/__main__.py +8 -0
- netparse/cli/all.py +32 -0
- netparse/cli/diff.py +1351 -0
- netparse/cli/parse.py +216 -0
- netparse/cli/readonly.py +158 -0
- netparse/cli/route_forms.py +255 -0
- netparse/engine.py +1834 -0
- netparse/masking.py +163 -0
- netparse/paths.py +48 -0
- netparse/py.typed +0 -0
- netparse_cmdb-0.8.0.dist-info/METADATA +221 -0
- netparse_cmdb-0.8.0.dist-info/RECORD +21 -0
- netparse_cmdb-0.8.0.dist-info/WHEEL +5 -0
- netparse_cmdb-0.8.0.dist-info/entry_points.txt +2 -0
- netparse_cmdb-0.8.0.dist-info/licenses/LICENSE +21 -0
- netparse_cmdb-0.8.0.dist-info/top_level.txt +1 -0
netparse/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""netparse —— 网络设备配置解析器。
|
|
2
|
+
|
|
3
|
+
把华为 / 中兴 / Nokia 等设备的**配置文件**按模板 DSL 解析成结构化 JSON,
|
|
4
|
+
用于 CMDB 与接口台账。
|
|
5
|
+
|
|
6
|
+
设计要点
|
|
7
|
+
--------
|
|
8
|
+
* **嵌套状态栈**:模板用缩进表达层级,每层声明 `start` / `end` / `[value]` / `[rule]`。
|
|
9
|
+
* **块分隔符**:裸 `#` / `!` 是块分隔符(不是注释),参与 end 出栈。
|
|
10
|
+
* **凭据脱敏**:模板 `type(secret)` 精确遮蔽(L1)+ 密文形态兜底(L2),
|
|
11
|
+
遮蔽发生在写入前,记录对象里不存在明文。
|
|
12
|
+
|
|
13
|
+
快速开始
|
|
14
|
+
--------
|
|
15
|
+
::
|
|
16
|
+
|
|
17
|
+
from netparse import parse_template, run
|
|
18
|
+
|
|
19
|
+
colls = parse_template("templates/huawei-vrp.cmdb")
|
|
20
|
+
result = run(colls, open("device.cfg", encoding="utf-8").readlines())
|
|
21
|
+
print(result["Interfaces"][0]["Name"])
|
|
22
|
+
|
|
23
|
+
命令行::
|
|
24
|
+
|
|
25
|
+
netparse parse <模板> <配置文件> --json
|
|
26
|
+
netparse lint <模板>
|
|
27
|
+
netparse diff --all --jobs 8
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from . import masking
|
|
31
|
+
from .engine import (
|
|
32
|
+
CONFIG,
|
|
33
|
+
CREDENTIAL_KEYWORDS,
|
|
34
|
+
TYPE_CONFLICT_KEY,
|
|
35
|
+
Coll,
|
|
36
|
+
CompiledRule,
|
|
37
|
+
Field,
|
|
38
|
+
Frame,
|
|
39
|
+
Rule,
|
|
40
|
+
apply_defaults,
|
|
41
|
+
apply_writes,
|
|
42
|
+
check_required,
|
|
43
|
+
compile_rule,
|
|
44
|
+
convert,
|
|
45
|
+
get_path,
|
|
46
|
+
is_coll_decl,
|
|
47
|
+
lint,
|
|
48
|
+
merge_by_key,
|
|
49
|
+
parse_literal,
|
|
50
|
+
parse_modifiers,
|
|
51
|
+
parse_target,
|
|
52
|
+
parse_template,
|
|
53
|
+
run,
|
|
54
|
+
set_path,
|
|
55
|
+
split_tokens,
|
|
56
|
+
)
|
|
57
|
+
from .masking import (
|
|
58
|
+
MASK_DEFAULT,
|
|
59
|
+
SECRET_SHAPE_PATTERNS,
|
|
60
|
+
STATS,
|
|
61
|
+
MaskingStats,
|
|
62
|
+
is_secret_shape,
|
|
63
|
+
mask_value,
|
|
64
|
+
reset_stats,
|
|
65
|
+
should_mask_by_shape,
|
|
66
|
+
)
|
|
67
|
+
from .paths import (
|
|
68
|
+
baseline_template,
|
|
69
|
+
change_dir,
|
|
70
|
+
default_template,
|
|
71
|
+
repo_root,
|
|
72
|
+
templates_dir,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
__version__ = "0.8.0"
|
|
76
|
+
|
|
77
|
+
__all__ = [
|
|
78
|
+
# 引擎主流程
|
|
79
|
+
"parse_template", "run", "lint", "compile_rule",
|
|
80
|
+
# 模型
|
|
81
|
+
"Field", "Coll", "Rule", "CompiledRule", "Frame",
|
|
82
|
+
# 文法工具
|
|
83
|
+
"split_tokens", "parse_modifiers", "is_coll_decl", "parse_literal",
|
|
84
|
+
"parse_target", "convert", "get_path", "set_path", "apply_writes",
|
|
85
|
+
"check_required", "merge_by_key", "apply_defaults",
|
|
86
|
+
# 常量
|
|
87
|
+
"TYPE_CONFLICT_KEY", "CREDENTIAL_KEYWORDS",
|
|
88
|
+
# 脱敏
|
|
89
|
+
"masking", "CONFIG", "MASK_DEFAULT", "STATS", "MaskingStats",
|
|
90
|
+
"SECRET_SHAPE_PATTERNS", "is_secret_shape", "should_mask_by_shape",
|
|
91
|
+
"mask_value", "reset_stats",
|
|
92
|
+
# 路径
|
|
93
|
+
"repo_root", "templates_dir", "change_dir", "default_template", "baseline_template",
|
|
94
|
+
# 版本
|
|
95
|
+
"__version__",
|
|
96
|
+
]
|
netparse/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""形状适配器"""
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""netparse 结果 → incumbent 形状 的**纯结构**适配器(design.md D1 / D9)
|
|
2
|
+
|
|
3
|
+
为什么需要它
|
|
4
|
+
------------
|
|
5
|
+
netparse 的模板风格(PascalCase 字段名 + 声明式集合)是它相对 incumbent 的**唯一优势**;
|
|
6
|
+
为了比对而把模板改成 incumbent 的 snake_case,等于自毁优势(D1)。
|
|
7
|
+
所以加一层**一次性、单向、可测**的纯映射:netparse JSON → incumbent JSON 形状,
|
|
8
|
+
然后两侧都喂给 incumbent 的 `build_rows`(口径一致,diff 才可信)。
|
|
9
|
+
|
|
10
|
+
D9 铁律:**只做「键改名 + 结构重排 + 值搬运」**
|
|
11
|
+
· 禁止推导、计算、默认值填充
|
|
12
|
+
· 禁止把一个字段拆成多个 / 把多个字段合并
|
|
13
|
+
· **禁止**"netparse 没抓到 → 适配器补一个合理默认值"
|
|
14
|
+
(唯一例外是 design.md 明确允许的:路由缺 `NextHop`/`NextHopIface` → 空串 "",
|
|
15
|
+
因为 incumbent 侧就是空串 —— 这是「值搬运」不是合成)
|
|
16
|
+
|
|
17
|
+
映射表 `MAPPING_SPEC` 是**权威表**,不是注释
|
|
18
|
+
--------------------------------------------
|
|
19
|
+
代码里的取值**全部经由本表的 `source` 路径解析** ⇒ 改错一条 `source`,
|
|
20
|
+
对应样例立刻失败(tasks.md 2.1.3 的验收)。`root_cause_if_empty` 同时充当
|
|
21
|
+
D8 的**待验证根因假设**。报告不得直接据此自动判定根因;
|
|
22
|
+
自动分类必须另有真实输入、模板声明与真实 trace 证据。
|
|
23
|
+
|
|
24
|
+
`source` 路径语法
|
|
25
|
+
-----------------
|
|
26
|
+
"Device[0].SysName" 根级取值([0] = 取第 0 个)
|
|
27
|
+
"Interfaces[].Name" 逐集合元素取值
|
|
28
|
+
"Interfaces[].IpAddress[].Address" 两层 list 展开
|
|
29
|
+
可选 filter={"field": "Family", "value": "ipv4"} —— 作用在**最后一层 list 展开**的元素上
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
# 段二(能力口径)用:netparse 的字段名 → incumbent 的字段名(语义别名,非大小写折叠)
|
|
33
|
+
# design.md:比较前必须按语义别名表归一化;PascalCase ↔ snake_case 不能靠折叠大小写
|
|
34
|
+
FIELD_ALIASES = {
|
|
35
|
+
"Name": "name",
|
|
36
|
+
"Description": "description",
|
|
37
|
+
"IpAddress": "IP",
|
|
38
|
+
"IpBindingVpn": "vpn",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
#: 映射表:id → (incumbent 路径, netparse 来源, 台账列, 缺值根因, 备注)
|
|
42
|
+
MAPPING_SPEC = [
|
|
43
|
+
# ── 设备级 ───────────────────────────────────────────
|
|
44
|
+
{"id": "device_name", "path": "device_name", "source": "Device[0].SysName",
|
|
45
|
+
"column": "设备名称", "root_cause_if_empty": "字段丢失",
|
|
46
|
+
"note": "顶层设备级;netparse 的 Device 集合是 dict 型"},
|
|
47
|
+
{"id": "device_ip", "path": "device_ip", "source": "Device[0].RouterId",
|
|
48
|
+
"column": "管理IP", "root_cause_if_empty": "字段丢失",
|
|
49
|
+
"note": "顶层设备级"},
|
|
50
|
+
|
|
51
|
+
# ── 接口级 ───────────────────────────────────────────
|
|
52
|
+
{"id": "interfaces[].name", "path": "interfaces[].name",
|
|
53
|
+
"source": "Interfaces[].Name", "column": "接口",
|
|
54
|
+
"root_cause_if_empty": "字段丢失",
|
|
55
|
+
"note": "台账主键;两侧按此 join(D11)"},
|
|
56
|
+
{"id": "interfaces[].description", "path": "interfaces[].description",
|
|
57
|
+
"source": "Interfaces[].Description", "column": "接口描述",
|
|
58
|
+
"root_cause_if_empty": "字段丢失",
|
|
59
|
+
"note": "netparse 没有该字段时不产生 description 键(与 incumbent 的键存在性一致)"},
|
|
60
|
+
|
|
61
|
+
# ── 接口 IP ──────────────────────────────────────────
|
|
62
|
+
{"id": "interfaces[].IP.IPV4[].ip", "path": "interfaces[].IP.IPV4[].ip",
|
|
63
|
+
"source": "Interfaces[].IpAddress[].Address",
|
|
64
|
+
"filter": {"field": "Family", "value": "ipv4"},
|
|
65
|
+
"column": "端口IPv4", "root_cause_if_empty": "字段丢失",
|
|
66
|
+
"note": "IP 是 dict(IPV4/IPV6 两个列表)"},
|
|
67
|
+
{"id": "interfaces[].IP.IPV4[].mask", "path": "interfaces[].IP.IPV4[].mask",
|
|
68
|
+
"source": "Interfaces[].IpAddress[].Mask",
|
|
69
|
+
"filter": {"field": "Family", "value": "ipv4"},
|
|
70
|
+
"column": "端口IPv4", "root_cause_if_empty": "字段丢失",
|
|
71
|
+
"note": "掩码转 CIDR 由 build_rows 做,适配器不碰"},
|
|
72
|
+
{"id": "interfaces[].IP.IPV4[].type", "path": "interfaces[].IP.IPV4[].type",
|
|
73
|
+
"source": "Interfaces[].IpAddress[].AddressType",
|
|
74
|
+
"filter": {"field": "Family", "value": "ipv4"},
|
|
75
|
+
"column": "端口IPv4", "root_cause_if_empty": "字段丢失",
|
|
76
|
+
"note": "D3:secondary 地址(sub)。主地址无该键、副地址为 'sub' —— "
|
|
77
|
+
"与 incumbent 的键存在性语义逐字一致;修前是模板未覆盖(sub 被正则吃掉)"},
|
|
78
|
+
{"id": "interfaces[].IP.IPV6[].ip", "path": "interfaces[].IP.IPV6[].ip",
|
|
79
|
+
"source": "Interfaces[].IpAddress[].Address",
|
|
80
|
+
"filter": {"field": "Family", "value": "ipv6"},
|
|
81
|
+
"column": "端口IPv6", "root_cause_if_empty": "字段丢失",
|
|
82
|
+
"note": "incumbent 实测 IPv6 元素键是 ip(不是 addr),build_rows 两者都认"},
|
|
83
|
+
{"id": "interfaces[].IP.IPV6[].mask", "path": "interfaces[].IP.IPV6[].mask",
|
|
84
|
+
"source": "Interfaces[].IpAddress[].Mask",
|
|
85
|
+
"filter": {"field": "Family", "value": "ipv6"},
|
|
86
|
+
"column": "端口IPv6", "root_cause_if_empty": "字段丢失",
|
|
87
|
+
"note": "前缀长度(incumbent 侧叫 mask)"},
|
|
88
|
+
|
|
89
|
+
# ── VPN ─────────────────────────────────────────────
|
|
90
|
+
{"id": "interfaces[].vpn.name", "path": "interfaces[].vpn.name",
|
|
91
|
+
"source": "Interfaces[].IpBindingVpn", "column": "VPN实例",
|
|
92
|
+
"root_cause_if_empty": "字段丢失",
|
|
93
|
+
"note": "无值则不产生 vpn 键(incumbent 侧也是键缺失)"},
|
|
94
|
+
|
|
95
|
+
# ── 静态路由 ─────────────────────────────────────────
|
|
96
|
+
{"id": "route-static.IPV4[].dest", "path": "route-static.IPV4[].dest",
|
|
97
|
+
"source": "RouteStatics[].Prefix", "column": "IPv4静态路由明细",
|
|
98
|
+
"root_cause_if_empty": "字段丢失", "note": "route-static 在 incumbent 侧是 dict 不是 list"},
|
|
99
|
+
{"id": "route-static.IPV4[].mask", "path": "route-static.IPV4[].mask",
|
|
100
|
+
"source": "RouteStatics[].Mask", "column": "IPv4静态路由明细",
|
|
101
|
+
"root_cause_if_empty": "字段丢失", "note": "掩码转 CIDR 由 build_rows 做"},
|
|
102
|
+
{"id": "route-static.IPV4[].nexthop", "path": "route-static.IPV4[].nexthop",
|
|
103
|
+
"source": "RouteStatics[].NextHop", "column": "IPv4静态路由明细",
|
|
104
|
+
"root_cause_if_empty": "字段丢失",
|
|
105
|
+
"note": "「只有出接口」形态下 incumbent 是空串、netparse 是键缺失 → 映射成空串(D9 允许的值搬运)"},
|
|
106
|
+
{"id": "route-static.IPV4[].interface", "path": "route-static.IPV4[].interface",
|
|
107
|
+
"source": "RouteStatics[].NextHopIface", "column": "IPv4静态路由明细",
|
|
108
|
+
"root_cause_if_empty": "整条记录丢失",
|
|
109
|
+
"note": "根因是「整条记录丢失」不是「字段丢失」—— 修前带出接口的路由整条没进结果;"
|
|
110
|
+
"台账第 10 列只收带出接口的路由,所以影响 ≈ 100%"},
|
|
111
|
+
{"id": "route-static.IPV4[].vpn", "path": "route-static.IPV4[].vpn",
|
|
112
|
+
"source": "RouteStatics[].VpnInstance", "column": "IPv4静态路由明细",
|
|
113
|
+
"root_cause_if_empty": "字段丢失", "note": "VPN 实例名"},
|
|
114
|
+
{"id": "route-static.IPV6[]", "path": "route-static.IPV6[]", "source": None,
|
|
115
|
+
"column": "IPv6静态路由明细", "root_cause_if_empty": "模板未覆盖该命令",
|
|
116
|
+
"note": "netparse 模板无 ipv6 route-static 规则;台账第 11 列必然空"},
|
|
117
|
+
|
|
118
|
+
# ── 限速三层(缺一不可)──────────────────────────────
|
|
119
|
+
{"id": "qos-profile[]", "path": "qos-profile[]", "source": None,
|
|
120
|
+
"column": "接口入流限速(M)/接口出流限速(M)", "root_cause_if_empty": "模板未覆盖该命令",
|
|
121
|
+
"note": "限速第 1/3 层:顶层命名空间级定义 list[{name,in:{cir},out:{cir}}]"},
|
|
122
|
+
{"id": "interfaces[].qos-profile.in", "path": "interfaces[].qos-profile.in", "source": None,
|
|
123
|
+
"column": "接口入流限速(M)", "root_cause_if_empty": "模板未覆盖该命令",
|
|
124
|
+
"note": "限速第 2/3 层:接口级引用名(值是名字)"},
|
|
125
|
+
{"id": "interfaces[].qos-profile.out", "path": "interfaces[].qos-profile.out", "source": None,
|
|
126
|
+
"column": "接口出流限速(M)", "root_cause_if_empty": "模板未覆盖该命令",
|
|
127
|
+
"note": "限速第 2/3 层:接口级引用名(值是名字)"},
|
|
128
|
+
{"id": "interfaces[].QOS.in.car", "path": "interfaces[].QOS.in.car", "source": None,
|
|
129
|
+
"column": "接口入流限速(M)", "root_cause_if_empty": "模板未覆盖该命令",
|
|
130
|
+
"note": "限速第 3/3 层:接口级直给数值"},
|
|
131
|
+
{"id": "interfaces[].QOS.out.car", "path": "interfaces[].QOS.out.car", "source": None,
|
|
132
|
+
"column": "接口出流限速(M)", "root_cause_if_empty": "模板未覆盖该命令",
|
|
133
|
+
"note": "限速第 3/3 层:接口级直给数值"},
|
|
134
|
+
|
|
135
|
+
# ── VLAN 三列 ───────────────────────────────────────
|
|
136
|
+
{"id": "interfaces[].VLAN.user-vlan[].user-vlan",
|
|
137
|
+
"path": "interfaces[].VLAN.user-vlan[].user-vlan",
|
|
138
|
+
"source": "Interfaces[].UserVlan", "column": "CVLAN",
|
|
139
|
+
"root_cause_if_empty": "待人工判定",
|
|
140
|
+
"note": "VLAN ↔ UserVlan:只搬运已捕获的标量,不合成 type/QinQ/dot1q"},
|
|
141
|
+
{"id": "interfaces[].VLAN.type", "path": "interfaces[].VLAN.type", "source": None,
|
|
142
|
+
"column": "VLAN封装类型", "root_cause_if_empty": "模板未覆盖该命令",
|
|
143
|
+
"note": "dot1q / user-vlan / QinQ"},
|
|
144
|
+
{"id": "interfaces[].VLAN.QinQ[].qinq", "path": "interfaces[].VLAN.QinQ[].qinq", "source": None,
|
|
145
|
+
"column": "PVLAN", "root_cause_if_empty": "模板未覆盖该命令",
|
|
146
|
+
"note": "外层(业务叠加层)"},
|
|
147
|
+
{"id": "interfaces[].VLAN.dot1q", "path": "interfaces[].VLAN.dot1q", "source": None,
|
|
148
|
+
"column": "CVLAN", "root_cause_if_empty": "模板未覆盖该命令",
|
|
149
|
+
"note": "内层兜底"},
|
|
150
|
+
|
|
151
|
+
# ── 业务属性三列 ─────────────────────────────────────
|
|
152
|
+
{"id": "interfaces[].bas.damian", "path": "interfaces[].bas.damian", "source": None,
|
|
153
|
+
"column": "域名名称", "root_cause_if_empty": "模板未覆盖该命令",
|
|
154
|
+
"note": "bas 块实测 514 行、模板 0 命中"},
|
|
155
|
+
{"id": "interfaces[].multicast.type", "path": "interfaces[].multicast.type", "source": None,
|
|
156
|
+
"column": "组播类型", "root_cause_if_empty": "模板未覆盖该命令",
|
|
157
|
+
"note": "multicast 块"},
|
|
158
|
+
{"id": "interfaces[].traffic-policy.in", "path": "interfaces[].traffic-policy.in",
|
|
159
|
+
"source": None, "column": "入方向流量策略",
|
|
160
|
+
"root_cause_if_empty": "模板未覆盖该命令", "note": "traffic-policy 块"},
|
|
161
|
+
{"id": "interfaces[].traffic-policy.out", "path": "interfaces[].traffic-policy.out",
|
|
162
|
+
"source": None, "column": "出方向流量策略",
|
|
163
|
+
"root_cause_if_empty": "模板未覆盖该命令", "note": "traffic-policy 块"},
|
|
164
|
+
]
|
|
165
|
+
|
|
166
|
+
ENTRY = {e["id"]: e for e in MAPPING_SPEC}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ── 路径解析(映射表的 source → 实际取值)────────────────
|
|
170
|
+
def _walk(node, tokens, filt, out, parent=None):
|
|
171
|
+
"""按 tokens 逐层取值;在最后一个 list 展开时套用 filter。"""
|
|
172
|
+
if not tokens:
|
|
173
|
+
out.append((parent, node))
|
|
174
|
+
return
|
|
175
|
+
tok = tokens[0]
|
|
176
|
+
rest = tokens[1:]
|
|
177
|
+
if tok.endswith("[]"):
|
|
178
|
+
name = tok[:-2]
|
|
179
|
+
items = node.get(name) if isinstance(node, dict) else None
|
|
180
|
+
last_list = not any(t.endswith("[]") for t in rest)
|
|
181
|
+
for it in (items or []):
|
|
182
|
+
if filt and last_list:
|
|
183
|
+
if not isinstance(it, dict) or it.get(filt["field"]) != filt["value"]:
|
|
184
|
+
continue
|
|
185
|
+
_walk(it, rest, filt, out, it)
|
|
186
|
+
return
|
|
187
|
+
if tok.endswith("]") and "[" in tok:
|
|
188
|
+
name, _, idx = tok[:-1].partition("[")
|
|
189
|
+
val = node.get(name) if isinstance(node, dict) else None
|
|
190
|
+
try:
|
|
191
|
+
val = val[int(idx)]
|
|
192
|
+
except (TypeError, ValueError, IndexError):
|
|
193
|
+
val = None
|
|
194
|
+
_walk(val, rest, filt, out, val)
|
|
195
|
+
return
|
|
196
|
+
val = node.get(tok) if isinstance(node, dict) else None
|
|
197
|
+
_walk(val, rest, filt, out, parent)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _tokens(source):
|
|
201
|
+
return source.split(".")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def resolve_values(root, source, filt=None):
|
|
205
|
+
"""从根取值 → [(父元素, 值)] 列表。"""
|
|
206
|
+
tokens = _tokens(source)
|
|
207
|
+
out = []
|
|
208
|
+
_walk(root, tokens, filt, out)
|
|
209
|
+
return out
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def resolve_item(item, source, filt=None):
|
|
213
|
+
"""从**集合元素**取值(source 的第一段是集合名,其余是元素内相对路径)。"""
|
|
214
|
+
tokens = _tokens(source)
|
|
215
|
+
rel = tokens[1:] if len(tokens) > 1 else []
|
|
216
|
+
out = []
|
|
217
|
+
_walk(item, rel, filt, out)
|
|
218
|
+
return out
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _first(pairs, default=None):
|
|
222
|
+
for _parent, val in pairs:
|
|
223
|
+
return val
|
|
224
|
+
return default
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _src(mid):
|
|
228
|
+
return ENTRY[mid]["source"]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _filt(mid):
|
|
232
|
+
return ENTRY[mid].get("filter")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _addr_entries(it, family):
|
|
236
|
+
"""某族(ipv4/ipv6)的地址条目。字段名来自映射表,族别来自映射表的 filter。"""
|
|
237
|
+
p = "interfaces[].IP.%s" % ("IPV4" if family == "ipv4" else "IPV6")
|
|
238
|
+
mid_ip, mid_mask = p + "[].ip", p + "[].mask"
|
|
239
|
+
f_ip = _src(mid_ip).split(".")[-1]
|
|
240
|
+
f_mask = _src(mid_mask).split(".")[-1]
|
|
241
|
+
# incumbent 的 type=sub 只属于 IPv4;IPv6 不得凭空添加该字段。
|
|
242
|
+
type_spec = ENTRY.get(p + "[].type")
|
|
243
|
+
f_type = type_spec["source"].split(".")[-1] if type_spec and type_spec["source"] else None
|
|
244
|
+
filt = _filt(mid_ip) or {"field": "Family", "value": family}
|
|
245
|
+
out = []
|
|
246
|
+
for parent, val in resolve_item(it, _src(mid_ip), filt):
|
|
247
|
+
elem = parent if isinstance(parent, dict) else {}
|
|
248
|
+
entry = {"ip": val if val is not None else elem.get(f_ip, ""),
|
|
249
|
+
"mask": elem.get(f_mask, "")}
|
|
250
|
+
if f_type is not None and f_type in elem:
|
|
251
|
+
entry["type"] = elem[f_type]
|
|
252
|
+
out.append(entry)
|
|
253
|
+
return out
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def to_incumbent_shape(np_result):
|
|
257
|
+
"""netparse 顶层结果 → incumbent 顶层 JSON 形状。
|
|
258
|
+
|
|
259
|
+
纯结构映射(D9):键改名 + 结构重排 + 值搬运;不合成、不推导、不填默认值。
|
|
260
|
+
"""
|
|
261
|
+
np_result = np_result or {}
|
|
262
|
+
out = {
|
|
263
|
+
"device_name": _first(resolve_values(np_result, _src("device_name"))) or "",
|
|
264
|
+
"device_ip": _first(resolve_values(np_result, _src("device_ip"))) or "",
|
|
265
|
+
"interfaces": [],
|
|
266
|
+
"route-static": {"IPV4": [], "IPV6": []},
|
|
267
|
+
# 顶层 qos-profile(限速第 1 层):netparse 模板没有 qos-profile 规则 → 空列表
|
|
268
|
+
"qos-profile": [],
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
for it in (np_result.get("Interfaces") or []):
|
|
272
|
+
d = {"name": _first(resolve_item(it, _src("interfaces[].name"))) or ""}
|
|
273
|
+
desc = _first(resolve_item(it, _src("interfaces[].description")))
|
|
274
|
+
if desc is not None:
|
|
275
|
+
d["description"] = desc
|
|
276
|
+
ip4 = _addr_entries(it, "ipv4")
|
|
277
|
+
ip6 = _addr_entries(it, "ipv6")
|
|
278
|
+
if ip4 or ip6:
|
|
279
|
+
d["IP"] = {"IPV4": ip4, "IPV6": ip6}
|
|
280
|
+
vpn = _first(resolve_item(it, _src("interfaces[].vpn.name")))
|
|
281
|
+
if vpn:
|
|
282
|
+
d["vpn"] = {"name": vpn}
|
|
283
|
+
user_vlan = _first(resolve_item(
|
|
284
|
+
it, _src("interfaces[].VLAN.user-vlan[].user-vlan")))
|
|
285
|
+
if user_vlan is not None:
|
|
286
|
+
# 标量 -> incumbent 的嵌套单值列表;其余 VLAN 子键不合成。
|
|
287
|
+
d["VLAN"] = {"user-vlan": [{"user-vlan": [user_vlan]}]}
|
|
288
|
+
out["interfaces"].append(d)
|
|
289
|
+
|
|
290
|
+
for r in (np_result.get("RouteStatics") or []):
|
|
291
|
+
out["route-static"]["IPV4"].append({
|
|
292
|
+
"dest": _first(resolve_item(r, _src("route-static.IPV4[].dest"))) or "",
|
|
293
|
+
"mask": _first(resolve_item(r, _src("route-static.IPV4[].mask"))) or "",
|
|
294
|
+
"nexthop": _first(resolve_item(r, _src("route-static.IPV4[].nexthop"))) or "",
|
|
295
|
+
"interface": _first(resolve_item(r, _src("route-static.IPV4[].interface"))) or "",
|
|
296
|
+
"vpn": _first(resolve_item(r, _src("route-static.IPV4[].vpn"))) or "",
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
return out
|
netparse/cli/__init__.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""netparse 命令行入口。
|
|
2
|
+
|
|
3
|
+
单一入口 + 子命令::
|
|
4
|
+
|
|
5
|
+
netparse parse <模板> <配置文件> [--json] [--mask-value M] [--no-mask-heuristic]
|
|
6
|
+
netparse lint <模板> [--json] [--strict]
|
|
7
|
+
netparse diff (--all | --sample N) [--jobs N] [...]
|
|
8
|
+
netparse route-forms [--sample N] [--file F]
|
|
9
|
+
netparse readonly (--capture | --verify)
|
|
10
|
+
|
|
11
|
+
子命令的实现分散在 `netparse.cli.*`,这样每个子命令可以独立 import,
|
|
12
|
+
不装可选依赖(如 diff 需要生产 build_excel)时其余子命令照常可用。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
from .. import __version__
|
|
19
|
+
|
|
20
|
+
SUBCOMMANDS = ("parse", "lint", "diff", "route-forms", "readonly", "all")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def preprocess_argv(argv):
|
|
24
|
+
"""解释器模式预处理:netparse main.np [...] → parse 子命令形态。"""
|
|
25
|
+
if not argv:
|
|
26
|
+
return argv
|
|
27
|
+
if argv[0] == "-m":
|
|
28
|
+
argv = argv[1:] # -m <子命令> ... → <子命令> ...
|
|
29
|
+
return argv
|
|
30
|
+
if argv[0] in SUBCOMMANDS or argv[0] == "all":
|
|
31
|
+
return argv # 旧子命令直通
|
|
32
|
+
if argv[0].startswith("-"):
|
|
33
|
+
return argv # 全局 flag(--version 等)
|
|
34
|
+
# ── 解释器模式:argv[0] 是模板路径 ──
|
|
35
|
+
template = argv[0]
|
|
36
|
+
rest = argv[1:]
|
|
37
|
+
has_cfg = bool(rest) and not rest[0].startswith("-")
|
|
38
|
+
if has_cfg:
|
|
39
|
+
return ["parse", template, rest[0]] + rest[1:]
|
|
40
|
+
return ["parse", template, "--selftest"] + rest
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_parser():
|
|
44
|
+
parser = argparse.ArgumentParser(
|
|
45
|
+
prog="netparse",
|
|
46
|
+
description="网络设备配置解析器(模板 DSL + 嵌套状态栈)",
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument("--version", action="version", version="netparse " + __version__)
|
|
49
|
+
sub = parser.add_subparsers(dest="command", metavar="{%s}" % ",".join(SUBCOMMANDS))
|
|
50
|
+
|
|
51
|
+
# ── parse ──
|
|
52
|
+
p = sub.add_parser("all", help="全量自测:递归执行目录内全部模板的 [__main__] 段")
|
|
53
|
+
p.add_argument("template", help="入口模板路径(同目录全部 .np/.cmdb 一起测)")
|
|
54
|
+
|
|
55
|
+
p = sub.add_parser("parse", help="按模板解析配置文件或配置文件夹")
|
|
56
|
+
p.add_argument("template", help="模板路径(.np / .cmdb)")
|
|
57
|
+
p.add_argument("config", nargs="?", default=None,
|
|
58
|
+
help="配置文件或配置文件夹(文件夹=递归解析全部文件);--selftest 时可省略")
|
|
59
|
+
p.add_argument("output", nargs="?", default=None,
|
|
60
|
+
help="输出 JSON 路径(可选;不指定则打印到 stdout)")
|
|
61
|
+
p.add_argument("--json", action="store_true", help="输出完整 JSON(stdout 保持纯 JSON)")
|
|
62
|
+
p.add_argument("--selftest", action="store_true",
|
|
63
|
+
help="只加载模板并执行 [__main__] 自测试段(不需要 config)")
|
|
64
|
+
p.add_argument("--mask-value", default=None, help="掩码串(默认 ******)")
|
|
65
|
+
p.add_argument("--no-mask-heuristic", action="store_true",
|
|
66
|
+
help="关闭 L2 密文形态兜底,只保留模板 type(secret) 的精确遮蔽")
|
|
67
|
+
p.add_argument("--fields", default=None,
|
|
68
|
+
help="字段白名单(输出层裁剪):集合=字段1,字段2;多组用 ; 分隔"
|
|
69
|
+
"(例:Interfaces=Name,Type,IpAddress;RouteStatics=Prefix,Mask,NextHop;"
|
|
70
|
+
"集合名单独出现=保留全部字段;Key 字段自动保留)")
|
|
71
|
+
|
|
72
|
+
# ── lint ──
|
|
73
|
+
p = sub.add_parser("lint", help="模板体检(不解析配置)")
|
|
74
|
+
p.add_argument("template", help="模板路径(.np / .cmdb)")
|
|
75
|
+
p.add_argument("--json", action="store_true", help="以 JSON 输出问题列表")
|
|
76
|
+
p.add_argument("--strict", action="store_true", help="有「警告」也返回非零退出码")
|
|
77
|
+
|
|
78
|
+
# 其余子命令的解析器在各自模块里,惰性注册(避免 import 不到的依赖直接炸主入口)
|
|
79
|
+
for name, module, func in (
|
|
80
|
+
("diff", "diff", "add_arguments"),
|
|
81
|
+
("route-forms", "route_forms", "add_arguments"),
|
|
82
|
+
("readonly", "readonly", "add_arguments"),
|
|
83
|
+
):
|
|
84
|
+
sp = sub.add_parser(name, help="见 `netparse %s --help`" % name)
|
|
85
|
+
sp.set_defaults(_lazy=(module, func))
|
|
86
|
+
|
|
87
|
+
return parser
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _inject_lazy_args(parser, argv):
|
|
91
|
+
"""把子命令专属参数的定义推迟到真正要用时才 import。
|
|
92
|
+
|
|
93
|
+
diff / route-forms / readonly 依赖生产只读目录或外部脚本,环境不满足时
|
|
94
|
+
仍应能 `netparse parse`。所以先由主解析器识别子命令,再交给子模块补参数。
|
|
95
|
+
"""
|
|
96
|
+
if not argv:
|
|
97
|
+
return None
|
|
98
|
+
name = argv[0]
|
|
99
|
+
if name not in ("diff", "route-forms", "readonly"):
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
import importlib
|
|
103
|
+
module = importlib.import_module(
|
|
104
|
+
"." + {"diff": "diff", "route-forms": "route_forms",
|
|
105
|
+
"readonly": "readonly"}[name],
|
|
106
|
+
package=__name__)
|
|
107
|
+
|
|
108
|
+
sp = argparse.ArgumentParser(prog="netparse " + name, description=module.__doc__,
|
|
109
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
110
|
+
sp.add_argument("--version", action="version", version="netparse " + __version__)
|
|
111
|
+
module.add_arguments(sp)
|
|
112
|
+
return name, module, sp
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def main(argv=None):
|
|
116
|
+
argv = preprocess_argv(list(sys.argv[1:] if argv is None else argv))
|
|
117
|
+
|
|
118
|
+
if argv and argv[0] == "all":
|
|
119
|
+
from . import all as _all
|
|
120
|
+
ap = build_parser()
|
|
121
|
+
args = ap.parse_args(argv)
|
|
122
|
+
return _all.main(args)
|
|
123
|
+
|
|
124
|
+
lazy = _inject_lazy_args(None, argv)
|
|
125
|
+
if lazy is not None:
|
|
126
|
+
name, module, sp = lazy
|
|
127
|
+
args = sp.parse_args(argv[1:])
|
|
128
|
+
return module.main(args)
|
|
129
|
+
|
|
130
|
+
parser = build_parser()
|
|
131
|
+
args = parser.parse_args(argv)
|
|
132
|
+
if not args.command:
|
|
133
|
+
parser.print_help()
|
|
134
|
+
return 1
|
|
135
|
+
|
|
136
|
+
if args.command == "parse":
|
|
137
|
+
from . import parse
|
|
138
|
+
return parse.main(args)
|
|
139
|
+
if args.command == "lint":
|
|
140
|
+
from . import parse as parse_mod
|
|
141
|
+
return parse_mod.main_lint(args)
|
|
142
|
+
|
|
143
|
+
parser.error("未知子命令:%s" % args.command)
|
|
144
|
+
return 2
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
if __name__ == "__main__":
|
|
148
|
+
sys.exit(main())
|
netparse/cli/__main__.py
ADDED
netparse/cli/all.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""netparse -m all <入口模板>:全量自测(递归子模板的 [__main__] 段)。"""
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from ..engine import parse_template, TemplateFileError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(args):
|
|
9
|
+
entry = os.path.abspath(args.template)
|
|
10
|
+
if not os.path.isfile(entry):
|
|
11
|
+
print("[FAIL] 入口模板不存在: %s" % entry)
|
|
12
|
+
return 2
|
|
13
|
+
tpl_dir = os.path.dirname(entry)
|
|
14
|
+
nps = sorted(fn for fn in os.listdir(tpl_dir) if fn.endswith((".np", ".cmdb")))
|
|
15
|
+
passed, failed, results = 0, 0, []
|
|
16
|
+
for fn in nps:
|
|
17
|
+
path = os.path.join(tpl_dir, fn)
|
|
18
|
+
try:
|
|
19
|
+
parse_template(path) # [__main__] 段在加载时执行;异常 = FAIL
|
|
20
|
+
passed += 1
|
|
21
|
+
results.append("[PASS] %s" % fn)
|
|
22
|
+
except TemplateFileError as e:
|
|
23
|
+
failed += 1
|
|
24
|
+
results.append("[FAIL] %s: %s" % (fn, str(e).split(": ", 1)[-1][:120]))
|
|
25
|
+
except Exception as e:
|
|
26
|
+
failed += 1
|
|
27
|
+
results.append("[FAIL] %s: %s: %s" % (fn, type(e).__name__, e))
|
|
28
|
+
for line in results:
|
|
29
|
+
print(line)
|
|
30
|
+
print("---")
|
|
31
|
+
print("全量自测: %d PASS / %d FAIL(共 %d)" % (passed, failed, passed + failed))
|
|
32
|
+
return 1 if failed else 0
|