-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore_logic.py
More file actions
1514 lines (1354 loc) · 58.4 KB
/
Copy pathcore_logic.py
File metadata and controls
1514 lines (1354 loc) · 58.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# core_logic.py
import zipfile
import xml.etree.ElementTree as ET
import socket
import time
import re
import tempfile
import os
import logging
from config import Config
from network_utils import (
_is_prompt_line,
_flush_buffer,
_handle_more_prompt,
_send_and_wait,
_ensure_user_view,
send_command,
_wait_for_prompt,
_is_prompt_at_user_view,
_execute_command,
_has_command_error,
)
logger = logging.getLogger(__name__)
# ========== 1. Topo 解析(增强版) ==========
def parse_topo(file_path):
logger.info(f'开始解析拓扑文件: {file_path}')
root = None
try:
with open(file_path, 'rb') as f:
raw_data = f.read()
logger.info('文件读取成功')
except Exception as e:
logger.error(f'读取文件失败: {str(e)}')
return {"status": "error", "msg": f"读取文件失败: {str(e)}"}
# 尝试多种编码解码(需能解析为合法 XML,避免 utf-16 误匹配 utf-8)
xml_text = None
last_xml_error = None
for enc in ['utf-8-sig', 'utf-16', 'utf-8', 'gbk']:
try:
candidate = raw_data.decode(enc)
if candidate.startswith('\ufeff'):
candidate = candidate[1:]
candidate = re.sub(r'<\?xml.*?\?>', '', candidate).strip()
ET.fromstring(candidate)
xml_text = candidate
logger.info(f'文件编码识别成功: {enc}')
break
except (UnicodeDecodeError, ET.ParseError) as e:
last_xml_error = e
continue
if xml_text is None:
# 可能是 ZIP 包装的拓扑
try:
with zipfile.ZipFile(file_path, 'r') as zip_ref:
logger.info(f'按 ZIP 处理,包含: {zip_ref.namelist()}')
for name in zip_ref.namelist():
if not name.lower().endswith('.xml') and not name.lower().endswith('.topo'):
continue
zraw = zip_ref.read(name)
for enc in ['utf-8-sig', 'utf-16', 'utf-8', 'gbk']:
try:
candidate = zraw.decode(enc)
if candidate.startswith('\ufeff'):
candidate = candidate[1:]
candidate = re.sub(r'<\?xml.*?\?>', '', candidate).strip()
ET.fromstring(candidate)
xml_text = candidate
logger.info(f'ZIP 内文件编码识别成功: {enc}')
break
except (UnicodeDecodeError, ET.ParseError):
continue
if xml_text:
break
except zipfile.BadZipFile:
logger.error('无法识别文件编码或 XML 无效: %s', last_xml_error)
return {"status": "error", "msg": "无法识别文件编码或 XML 无效"}
except Exception as e:
logger.error(f'ZIP 处理异常: {str(e)}')
return {"status": "error", "msg": f"ZIP 处理异常: {str(e)}"}
if xml_text is None:
logger.error('未能提取到有效 XML')
return {"status": "error", "msg": "未能提取到有效 XML"}
root = ET.fromstring(xml_text)
logger.info('XML 解析成功')
return _extract_topology_from_root(root)
def _safe_float(value, default=None):
if value is None or value == '':
return default
try:
return float(value)
except (TypeError, ValueError):
return default
def _safe_int(value, default=None):
if value is None or value == '':
return default
try:
return int(float(str(value).strip()))
except (TypeError, ValueError):
return default
def _build_device_interfaces(node):
"""根据 eNSP slot/interface 展开接口列表,下标与 line 的 srcIndex/tarIndex 对应。"""
interfaces = []
index = 0
# 新式逐条接口(CE/NE/USG6000V 等)
for iface in node.findall('.//interface'):
# count 批量定义与逐条定义区分:有 count 走下面批量逻辑
if iface.get('count') is not None:
continue
itype = iface.get('type') or iface.get('interfacename') or iface.get('sztype') or 'Ethernet'
slot_i = _safe_int(iface.get('slotIndex'), 0) or 0
card_i = _safe_int(iface.get('cardIndex'), 0) or 0
if_i = _safe_int(iface.get('interfaceIndex'))
if if_i is None:
if_i = index
prefix = _iface_prefix(itype)
# 槽位型:GE1/0/0 ;普通:GE0/0/0
if slot_i:
name = f'{prefix}{slot_i}/{card_i}/{if_i}'
else:
name = f'{prefix}0/0/{if_i}'
interfaces.append({'index': index, 'name': name, 'type': itype})
index += 1
# 旧式 count 批量接口(AR/S 系列)
if not interfaces:
for iface in node.findall('.//interface'):
count = _safe_int(iface.get('count'), 0) or 0
if count <= 0:
continue
itype = iface.get('interfacename') or iface.get('sztype') or iface.get('type') or 'Ethernet'
prefix = _iface_prefix(itype)
for i in range(count):
# 与 eNSP 常见编号一致:GE0/0/0 起
name = f'{prefix}0/0/{i}' if prefix in ('GE', 'Ethernet', '10GE', 'XGE') else f'{prefix}0/0/{i}'
# Serial 也用 Serial0/0/0
interfaces.append({'index': index, 'name': name, 'type': itype})
index += 1
return interfaces
def _iface_prefix(itype):
t = str(itype or '').upper()
if '10GE' in t or 'XGE' in t:
return '10GE'
if t in ('GE', 'GIGABITETHERNET') or 'GE' == t or t.startswith('GE'):
return 'GE'
if 'ETHERNET' in t or t == 'ETH':
return 'Ethernet'
if 'SERIAL' in t:
return 'Serial'
if 'ETH-TRUNK' in t or 'TRUNK' in t:
return 'Eth-Trunk'
return itype or 'Ethernet'
def _iface_name_by_index(interfaces, idx):
if idx is None:
return None
for item in interfaces or []:
if item.get('index') == idx:
return item.get('name')
# 兜底:按下标直接取
if isinstance(idx, int) and 0 <= idx < len(interfaces or []):
return interfaces[idx].get('name')
return f'if{idx}'
def _extract_topology_from_root(root):
"""从 eNSP topo XML 提取设备、坐标、链路与标签。"""
nodes = root.findall('.//dev') + root.findall('.//Device') + root.findall('.//node')
logger.info(f'找到 {len(nodes)} 个设备节点')
if not nodes:
devices_node = root.find('.//devices')
if devices_node is not None:
nodes = list(devices_node.findall('dev')) + list(devices_node.findall('Device'))
logger.info(f'从 devices 节点找到 {len(nodes)} 个设备节点')
if not nodes:
logger.error('文件中未找到任何设备节点')
return {"status": "error", "msg": "文件中未找到任何设备节点"}
all_devices = []
console_devices = []
device_if_map = {}
for idx, node in enumerate(nodes):
dev_name = node.get('name', 'Unknown')
dev_type = node.get('model') or node.get('type', 'Unknown')
port_str = node.get('com_port') or node.get('cxPort') or node.get('console') or node.get('port')
port_int = _safe_int(port_str, 0) or 0
cx = _safe_float(node.get('cx'))
cy = _safe_float(node.get('cy'))
if cx is None:
cx = _safe_float(node.get('edit_left'))
if cy is None:
cy = _safe_float(node.get('edit_top'))
if cx is None:
cx = 120.0 + (idx % 6) * 160.0
if cy is None:
cy = 120.0 + (idx // 6) * 140.0
dev_id = node.get('id') or f'dev-{idx}-{dev_name}'
interfaces = _build_device_interfaces(node)
device_if_map[dev_id] = interfaces
item = {
'id': dev_id,
'name': dev_name,
'type': dev_type,
'port': port_int if port_int else None,
'cx': cx,
'cy': cy,
'configurable': bool(port_int and port_int != 0),
'interfaces': interfaces
}
all_devices.append(item)
if item['configurable']:
console_devices.append({
'id': dev_id,
'name': dev_name,
'type': dev_type,
'port': port_int,
'cx': cx,
'cy': cy,
'interfaces': interfaces
})
logger.info(f'添加可配置设备: {dev_name} (类型: {dev_type}, 端口: {port_int}, 接口数: {len(interfaces)})')
if not console_devices:
logger.error('未找到包含有效控制台端口(非0)的网络设备')
return {"status": "error", "msg": "未找到包含有效控制台端口(非0)的网络设备"}
# 链路:兼容 <line> 与 <link>
links = []
line_nodes = root.findall('.//line') + root.findall('.//Line') + root.findall('.//link')
for line in line_nodes:
src = line.get('srcDeviceID') or line.get('src') or line.get('source')
dst = line.get('destDeviceID') or line.get('dst') or line.get('dest') or line.get('destination')
if not src or not dst:
src_el = line.find('.//source/device')
dst_el = line.find('.//destination/device')
if src_el is not None and src_el.text:
src = src_el.text.strip()
if dst_el is not None and dst_el.text:
dst = dst_el.text.strip()
if not src or not dst:
continue
pair = line.find('.//interfacePair')
media = 'Copper'
src_index = None
tar_index = None
if pair is not None:
media = pair.get('lineName') or media
src_index = _safe_int(pair.get('srcIndex'))
tar_index = _safe_int(pair.get('tarIndex'))
src_if = _iface_name_by_index(device_if_map.get(src), src_index)
dest_if = _iface_name_by_index(device_if_map.get(dst), tar_index)
links.append({
'src_id': src,
'dest_id': dst,
'media': media,
'src_index': src_index,
'tar_index': tar_index,
'src_if': src_if,
'dest_if': dest_if
})
# 文本标注(可选)
labels = []
for tip in root.findall('.//txttip') + root.findall('.//Txttip'):
content = tip.get('content') or ''
if not content.strip():
continue
labels.append({
'text': content.replace('\r\n', '\n').replace('\r', '\n'),
'left': _safe_float(tip.get('left'), 0),
'top': _safe_float(tip.get('top'), 0),
'right': _safe_float(tip.get('right'), 0),
'bottom': _safe_float(tip.get('bottom'), 0)
})
logger.info(
f'拓扑解析完成:可配置设备 {len(console_devices)},全部节点 {len(all_devices)},链路 {len(links)}'
)
return {
"status": "success",
"data": console_devices,
"topology": {
"devices": all_devices,
"links": links,
"labels": labels
}
}
# ========== 设备类型分类 ==========
SWITCH_TYPES = {
'S1700', 'S1720', 'S2700', 'S3700', 'S5700', 'S5720', 'S6700', 'S6720', 'S7700', 'S7900', 'S9700', 'S12700',
'S5700HI', 'S5710', 'S5720HI', 'S5730', 'S5735', 'S6730',
'CE5800', 'CE6800', 'CE6810', 'CE6850', 'CE6851', 'CE6855', 'CE6860', 'CE7850', 'CE12800',
'LSW'
}
ROUTER_TYPES = {
'AR120', 'AR120W', 'AR1220', 'AR1220V', 'AR1220W', 'AR156', 'AR169',
'AR2200', 'AR2220', 'AR2240', 'AR2240C', 'AR3260',
'AR6000', 'AR6100', 'AR6120', 'AR6140',
'NE20E', 'NE40E', 'NE80E', 'NE5000',
'Router'
}
FIREWALL_TYPES = {
'USG2110', 'USG2220', 'USG5120', 'USG5320', 'USG5520', 'USG6000V', 'USG6300', 'USG6500', 'USG6600', 'USG9500V',
'USG2000', 'USG5000', 'USG6000', 'USG9000',
'FW'
}
WLAN_TYPES = {
'AC6005', 'AC6605', 'ACU2', 'AC6508', 'AC6805', 'AC8005',
'AP2010DN', 'AP3010DN', 'AP4030DN', 'AP5030DN', 'AP6010DN', 'AP7030DE', 'AP8050DN',
'AP2010', 'AP3010', 'AP4030', 'AP5030', 'AP6010', 'AP7030', 'AP8050'
}
DEVICE_TECH_MAP = {
'switch': ['vlan', 'stp', 'eth_trunk', 'dhcp', 'virtual_interface', 'acl', 'vrrp'],
'l3_switch': [
'interface_ip', 'vlan', 'stp', 'eth_trunk', 'dhcp', 'virtual_interface',
'acl', 'vrrp', 'static_route', 'ospf', 'rip'
],
'router': [
'interface_ip', 'static_route', 'rip', 'ospf', 'bgp', 'isis', 'dhcp',
'virtual_interface', 'acl', 'nat', 'vrrp', 'eth_trunk'
],
'firewall': [
'interface_ip', 'static_route', 'ospf', 'bgp', 'acl', 'nat', 'dhcp',
'virtual_interface', 'vrrp', 'firewall_policy'
],
'wlan_ac': ['vlan', 'stp', 'dhcp', 'virtual_interface', 'acl', 'wlan'],
'unknown': [
'interface_ip', 'vlan', 'dhcp', 'virtual_interface', 'eth_trunk', 'stp',
'static_route', 'rip', 'ospf', 'bgp', 'isis', 'acl', 'nat', 'vrrp',
'wlan', 'firewall_policy'
]
}
L3_SWITCH_TYPES = {
'S5700', 'S5720', 'S6700', 'S6720', 'S7700', 'S7900', 'S9700', 'S12700',
'S5700HI', 'S5710', 'S5720HI', 'S5730', 'S5735', 'S6730',
'CE5800', 'CE6800', 'CE6810', 'CE6850', 'CE6851', 'CE6855', 'CE6860', 'CE7850', 'CE12800'
}
def classify_device(dev_type):
dt_upper = dev_type.upper().strip()
for prefix in SWITCH_TYPES:
if dt_upper.startswith(prefix) or dt_upper == prefix:
for l3_prefix in L3_SWITCH_TYPES:
if dt_upper.startswith(l3_prefix) or dt_upper == l3_prefix:
return 'l3_switch'
return 'switch'
for prefix in ROUTER_TYPES:
if dt_upper.startswith(prefix) or dt_upper == prefix:
return 'router'
for prefix in FIREWALL_TYPES:
if dt_upper.startswith(prefix) or dt_upper == prefix:
return 'firewall'
for prefix in WLAN_TYPES:
if dt_upper.startswith(prefix) or dt_upper == prefix:
if prefix.startswith('AP'):
return 'wlan_ac'
return 'wlan_ac'
dt_prefix = dt_upper.split('-')[0] if '-' in dt_upper else dt_upper.split()[0] if ' ' in dt_upper else dt_upper[:4]
if any(dt_prefix.startswith(kw) for kw in ['S5', 'S6', 'S7', 'S9', 'S12', 'CE']):
return 'l3_switch'
if any(dt_prefix.startswith(kw) for kw in ['S2', 'S3', 'S1']):
return 'switch'
if any(dt_prefix.startswith(kw) for kw in ['AR', 'NE']):
return 'router'
if 'ROUTER' in dt_upper:
return 'router'
if any(dt_prefix.startswith(kw) for kw in ['USG']):
return 'firewall'
if any(kw in dt_upper for kw in ['FW', 'FIREWALL']):
return 'firewall'
if any(dt_prefix.startswith(kw) for kw in ['AC', 'AP']):
return 'wlan_ac'
return 'unknown'
def get_available_techs(dev_type):
category = classify_device(dev_type)
return DEVICE_TECH_MAP.get(category, DEVICE_TECH_MAP['unknown'])
# ========== 2. 配置命令生成器(generators 包) ==========
from generators import CONFIG_GENERATORS, generate_annotated
# 兼容旧引用名
config_interface_ip = CONFIG_GENERATORS['interface_ip']
config_vlan = CONFIG_GENERATORS['vlan']
config_dhcp = CONFIG_GENERATORS['dhcp']
config_virtual_interface = CONFIG_GENERATORS['virtual_interface']
config_eth_trunk = CONFIG_GENERATORS['eth_trunk']
config_stp = CONFIG_GENERATORS['stp']
config_static_route = CONFIG_GENERATORS['static_route']
config_rip = CONFIG_GENERATORS['rip']
config_ospf = CONFIG_GENERATORS['ospf']
config_bgp = CONFIG_GENERATORS['bgp']
config_isis = CONFIG_GENERATORS['isis']
config_acl = CONFIG_GENERATORS['acl']
config_nat = CONFIG_GENERATORS['nat']
config_vrrp = CONFIG_GENERATORS['vrrp']
config_wlan = CONFIG_GENERATORS['wlan']
config_firewall_policy = CONFIG_GENERATORS['firewall_policy']
def validate_params(tech, params):
"""验证配置参数"""
logger.info(f'开始验证配置参数: 技术={tech}, 参数={params}')
if not isinstance(params, dict):
logger.error('参数类型错误,应为字典')
return {"valid": False, "error": "参数类型错误,应为字典"}
if tech not in CONFIG_GENERATORS:
logger.warning(f'未知的技术类型: {tech}')
return {"valid": False, "error": "未知的配置类型"}
if tech == 'interface_ip':
required = ['intf_name', 'ip_address', 'mask']
# 验证IP地址格式
if 'ip_address' in params:
ip = params['ip_address']
if not re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', ip):
return {"valid": False, "error": "IP地址格式错误"}
# 验证每个IP部分在0-255范围内
parts = ip.split('.')
for part in parts:
try:
num = int(part)
if num < 0 or num > 255:
return {"valid": False, "error": "IP地址格式错误"}
except ValueError:
return {"valid": False, "error": "IP地址格式错误"}
# 验证掩码格式
if 'mask' in params:
mask = params['mask']
if not (re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', mask) or re.match(r'^\d{1,2}$', mask)):
return {"valid": False, "error": "掩码格式错误"}
# 验证掩码值范围
if re.match(r'^\d{1,2}$', mask):
mask_num = int(mask)
if mask_num < 0 or mask_num > 32:
return {"valid": False, "error": "掩码范围应在0-32之间"}
elif tech == 'vlan':
# 兼容旧前端 vlan_action
operation = params.get('vlan_operation')
if not operation:
action = params.get('vlan_action', 'full')
operation = {
'create': 'create',
'assign': 'port_config',
'create_and_assign': 'full',
}.get(action, action if action in ('create', 'port_config', 'full') else 'full')
vlan_id = params.get('vlan_id') or params.get('trunk_allowed_vlans')
if operation in ('create', 'full'):
if not vlan_id:
return {"valid": False, "error": "VLAN ID不能为空"}
vlan_ids = [v.strip() for v in str(vlan_id).replace(',', ',').split(',') if v.strip()]
for vid in vlan_ids:
try:
vid_num = int(vid)
if vid_num < 1 or vid_num > 4094:
return {"valid": False, "error": "VLAN ID范围应在1-4094之间"}
except ValueError:
return {"valid": False, "error": "VLAN ID格式错误"}
if operation in ('port_config', 'full'):
if not params.get('interface') and not params.get('batch_ports'):
return {"valid": False, "error": "接口名不能为空"}
link_type = params.get('link_type', 'access')
if link_type in ('access', 'trunk') and operation == 'port_config' and not vlan_id:
return {"valid": False, "error": "端口配置需要指定 VLAN"}
required = []
elif tech == 'dhcp':
mode = params.get('mode', 'interface')
if mode == 'interface':
required = ['interface', 'dns']
else:
required = ['pool_name', 'gateway', 'network', 'mask', 'dns', 'interface']
# 验证DNS格式
if 'dns' in params:
dns_servers = [d.strip() for d in params['dns'].split(' ') if d.strip()]
for dns in dns_servers:
if not re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', dns):
return {"valid": False, "error": "DNS服务器地址格式错误"}
elif tech == 'virtual_interface':
vif_type = params.get('vif_type', 'vlanif')
if vif_type == 'vlanif':
required = ['vlan_id', 'ip', 'mask']
else:
required = ['loopback_id', 'ip', 'mask']
elif tech == 'eth_trunk':
required = ['trunk_id', 'member_interfaces']
elif tech == 'stp':
mode = params.get('stp_mode', 'stp').lower()
if mode == 'mstp':
required = ['stp_mode', 'region_name', 'instance_id', 'vlan_range']
else:
required = ['stp_mode']
elif tech == 'static_route':
if params.get('routes'):
required = []
else:
required = ['dest_network', 'mask']
if not params.get('next_hop') and not params.get('out_interface'):
logger.error('静态路由需要下一跳IP或出接口')
return {"valid": False, "error": "静态路由需要下一跳IP或出接口"}
elif tech == 'rip':
if params.get('networks') or params.get('network'):
required = []
else:
required = ['network']
elif tech == 'ospf':
if params.get('networks'):
required = ['router_id']
else:
required = ['router_id', 'network', 'wildcard_mask']
if 'router_id' in params and params['router_id']:
rid = params['router_id']
if not re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', rid):
return {"valid": False, "error": "Router ID格式错误"}
elif tech == 'bgp':
if params.get('peers') or params.get('networks'):
required = ['as_number', 'router_id']
if not params.get('peers') and not (params.get('peer_ip') and params.get('peer_as')):
return {"valid": False, "error": "至少配置一个 BGP 邻居"}
if not params.get('networks') and not (params.get('network') and params.get('mask')):
return {"valid": False, "error": "至少宣告一个网段"}
else:
required = ['as_number', 'router_id', 'peer_ip', 'peer_as', 'network', 'mask']
if 'as_number' in params and params['as_number']:
try:
as_num = int(params['as_number'])
if as_num < 1 or as_num > 65535:
return {"valid": False, "error": "AS号范围应在1-65535之间"}
except ValueError:
return {"valid": False, "error": "AS号格式错误"}
elif tech == 'isis':
if params.get('interfaces'):
required = ['net_entity']
else:
required = ['net_entity', 'interface']
elif tech == 'acl':
acl_type = params.get('acl_type', 'standard')
if acl_type == 'standard':
required = ['acl_num', 'rule_id', 'src_ip', 'src_wildcard']
else:
required = ['acl_num', 'rule_id', 'src_ip', 'src_wildcard', 'dst_ip', 'dst_wildcard']
if 'acl_num' in params and params['acl_num']:
try:
acl_num = int(params['acl_num'])
if not ((1000 <= acl_num <= 1999) or (2000 <= acl_num <= 2999) or (3000 <= acl_num <= 3999) or (4000 <= acl_num <= 4999)):
return {"valid": False, "error": "ACL编号范围错误"}
except ValueError:
return {"valid": False, "error": "ACL编号格式错误"}
elif tech == 'nat':
nat_mode = params.get('nat_mode', 'easyip')
if nat_mode == 'easyip':
required = ['acl_num', 'src_network', 'src_wildcard', 'out_interface']
else:
required = ['out_interface', 'protocol', 'global_port', 'inner_ip', 'inner_port']
elif tech == 'vrrp':
required = ['interface', 'vrid', 'virtual_ip']
if 'vrid' in params and params['vrid']:
try:
vrid = int(params['vrid'])
if vrid < 1 or vrid > 255:
return {"valid": False, "error": "VRID范围应在1-255之间"}
except ValueError:
return {"valid": False, "error": "VRID格式错误"}
elif tech == 'wlan':
required = [
'ssid_profile_name', 'ssid_name', 'security_profile_name',
'vap_profile_name', 'service_vlan', 'ap_group_name'
]
sec_mode = params.get('security_mode', 'wpa2_psk')
if sec_mode in ('psk', 'wpa2_psk', 'wpa3_sae', 'wpa3') and not params.get('psk_password'):
return {"valid": False, "error": "加密模式需要填写密码"}
elif tech == 'firewall_policy':
if params.get('trust_interface') or params.get('untrust_interface') or params.get('rule_only'):
required = ['rule_name'] if params.get('rule_only') else []
else:
required = ['trust_interface', 'untrust_interface']
else:
required = []
missing = [param for param in required if not params.get(param)]
if missing:
logger.error(f'缺少必要参数: {missing}')
return {"valid": False, "error": f"缺少必要参数: {', '.join(missing)}"}
logger.info('参数验证通过')
return {"valid": True, "error": None}
def generate_config(tech, params, device_category='unknown', preview=False, with_annotations=False):
"""生成配置命令。with_annotations=True 时返回 dict,否则返回命令字符串(兼容旧调用)。"""
logger.info(
f'开始生成配置: 技术={tech}, 参数={params}, 设备类别={device_category}, '
f'预览={preview}, 注解={with_annotations}'
)
validation = validate_params(tech, params)
if not validation["valid"]:
err = f"// 错误:{validation['error']}"
if with_annotations:
return {
'text': err + '\n',
'annotations': [{'cmd': err, 'explain': '参数校验失败'}],
'commands': [],
'error': validation['error'],
}
return err
result = generate_annotated(tech, params, device_category)
text = result['text']
if text.lstrip().startswith('// 错误'):
if with_annotations:
result['error'] = text.replace('// 错误:', '').strip()
return result
return text.strip() if not text.endswith('\n') else text.rstrip('\n')
logger.info(f'配置生成成功,命令行数: {len(result["commands"])}')
if preview:
text = f"// 预览模式\n{text}"
result = dict(result)
result['text'] = text
if with_annotations:
return result
return text
# ========== 3. Socket 通信辅助函数已移至 network_utils.py ==========
def push_to_device(port, commands):
host = Config.HOST
logger.info(f'开始推送配置到设备: 主机={host}, 端口={port}')
max_retries = Config.MAX_RETRIES
retry_interval = Config.RETRY_INTERVAL
for attempt in range(max_retries):
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(Config.SOCKET_TIMEOUT)
client.connect((host, port))
logger.info(f'设备连接成功 (尝试 {attempt + 1}/{max_retries})')
_flush_buffer(client)
_ensure_user_view(client)
cmd_lines = []
for line in commands.split('\n'):
line = line.strip()
if not line:
continue
if line.startswith('//') or line.startswith('#'):
continue
cmd_lines.append(line)
if not cmd_lines:
client.close()
return {"status": "error", "log": "没有可执行的命令"}
first_cmd = cmd_lines[0].lower().strip()
config_keywords = ['vlan', 'interface', 'ospf', 'bgp', 'rip', 'isis', 'acl', 'nat', 'stp', 'dhcp', 'qos', 'policy', 'traffic', 'firewall', 'undo', 'ip route', 'rip', 'aaa', 'user-interface', 'sysname', 'stp', 'vrrp', 'cluster', 'ntdp', 'ndp', 'diffserv', 'drop-profile']
if first_cmd != 'system-view' and any(first_cmd.startswith(kw) for kw in config_keywords):
cmd_lines.insert(0, 'system-view')
elif first_cmd == 'sysname' or first_cmd == 'clock' or first_cmd == 'language-mode':
cmd_lines.insert(0, 'system-view')
last_cmd = cmd_lines[-1].lower().strip()
if last_cmd != 'return' and last_cmd != 'quit' and last_cmd != 'system-view':
if last_cmd.startswith('interface ') or last_cmd.startswith('vlan '):
cmd_lines.append('return')
log_output = ""
error_occurred = False
total_cmds = len(cmd_lines)
logger.info(f'准备发送 {total_cmds} 条命令')
for cmd in cmd_lines:
log_output += f"> {cmd}\n"
try:
resp_text = _execute_command(client, cmd, timeout=Config.CMD_TIMEOUT)
log_output += resp_text
if _has_command_error(resp_text):
error_occurred = True
logger.warning(f'命令执行错误: {cmd}')
except Exception as cmd_error:
error_occurred = True
error_msg = f'命令执行异常: {str(cmd_error)}'
log_output += f"// {error_msg}\n"
logger.error(error_msg)
client.close()
# 分析执行结果
if error_occurred:
logger.warning('配置推送过程中出现错误')
return {"status": "error", "log": log_output}
else:
logger.info(f'配置推送完成,共发送 {total_cmds} 条命令')
return {"status": "success", "log": log_output}
except ConnectionRefusedError:
logger.error(f'连接被拒绝: 端口={port} (尝试 {attempt + 1}/{max_retries})')
if attempt < max_retries - 1:
logger.info(f'等待 {retry_interval} 秒后重试...')
time.sleep(retry_interval)
continue
else:
return {"status": "error", "log": f"连接被拒绝!请确认 eNSP 中设备已启动(绿色)。\n端口: {port}"}
except socket.timeout:
logger.error(f'连接超时: 端口={port} (尝试 {attempt + 1}/{max_retries})')
if attempt < max_retries - 1:
logger.info(f'等待 {retry_interval} 秒后重试...')
time.sleep(retry_interval)
continue
else:
return {"status": "error", "log": f"连接超时!请确认 eNSP 中设备已启动且可访问。\n端口: {port}"}
except Exception as e:
logger.error(f'连接设备发生错误: {str(e)} (尝试 {attempt + 1}/{max_retries})')
if attempt < max_retries - 1:
logger.info(f'等待 {retry_interval} 秒后重试...')
time.sleep(retry_interval)
continue
else:
return {"status": "error", "log": f"连接设备发生错误...\n错误信息: {str(e)}"}
# ========== 4. 读取设备接口列表(物理+虚拟) ==========
def get_device_interfaces(port):
host = Config.HOST
logger.info(f'开始获取设备接口列表: 主机={host}, 端口={port}')
max_retries = Config.MAX_RETRIES
retry_interval = Config.RETRY_INTERVAL
for attempt in range(max_retries):
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(Config.SOCKET_TIMEOUT)
client.connect((host, port))
logger.info(f'设备连接成功 (尝试 {attempt + 1}/{max_retries})')
_flush_buffer(client)
_ensure_user_view(client)
_send_and_wait(client, "system-view", timeout=5)
_send_and_wait(client, "quit", timeout=5)
output = _send_and_wait(client, "display interface brief", timeout=10)
client.close()
logger.info('接口信息获取成功')
physical = []
virtual = []
all_interfaces = []
for line in output.splitlines():
line = line.strip()
if not line:
continue
if line.startswith('Interface') or line.startswith('----'):
continue
if line.startswith('<') or line.startswith('['):
continue
if any(kw in line for kw in ['Physical', '*down:', '(l):', '(s):', '(b):', '^down:', '(e):', '(d):', 'InUti', 'PHY:', 'Error']):
continue
parts = line.split()
if not parts or len(parts) < 2:
continue
iface = parts[0]
if iface.startswith('display') or iface.startswith('Error'):
continue
if iface.startswith('Vlanif') or iface.startswith('LoopBack') or iface.startswith('NULL'):
virtual.append(iface)
elif (iface.startswith('GigabitEthernet') or iface.startswith('Ethernet') or
iface.startswith('Eth-Trunk') or iface.startswith('GE') or
iface.startswith('Serial') or iface.startswith('Cellular') or
iface.startswith('10GE') or iface.startswith('40GE') or iface.startswith('100GE') or
iface.startswith('XGigabitEthernet') or iface.startswith('FortyGigE')):
physical.append(iface)
elif '/' in iface and not iface.startswith('InUti'):
physical.append(iface)
else:
continue
all_interfaces.append(iface)
if not all_interfaces:
logger.warning(f'接口列表为空,可能解析失败 (尝试 {attempt + 1}/{max_retries})')
logger.debug(f'原始输出前500字符: {output[:500]}')
if attempt < max_retries - 1:
time.sleep(retry_interval)
continue
logger.info(f'接口列表解析完成: 物理接口={len(physical)}, 虚拟接口={len(virtual)}, 总接口={len(all_interfaces)}')
return {
"status": "success",
"interfaces": all_interfaces,
"physical": physical,
"virtual": virtual
}
except Exception as e:
logger.error(f'获取接口列表异常: {str(e)} (尝试 {attempt + 1}/{max_retries})')
if attempt < max_retries - 1:
logger.info(f'等待 {retry_interval} 秒后重试...')
time.sleep(retry_interval)
continue
else:
return {"status": "error", "msg": str(e)}
def save_device_config(port):
host = Config.HOST
logger.info(f'开始保存设备配置: 主机={host}, 端口={port}')
max_retries = Config.MAX_RETRIES
retry_interval = Config.RETRY_INTERVAL
for attempt in range(max_retries):
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(Config.SOCKET_TIMEOUT)
client.connect((host, port))
logger.info(f'设备连接成功 (尝试 {attempt + 1}/{max_retries})')
_flush_buffer(client)
_ensure_user_view(client)
client.sendall(b"save\n")
time.sleep(0.15) # 优化:减少初始等待时间
output = b""
client.settimeout(Config.CMD_TIMEOUT)
start = time.time()
confirmed = False
file_confirmed = False
max_wait_time = 15 # 优化:减少最大等待时间
while time.time() - start < max_wait_time:
try:
chunk = client.recv(4096)
if not chunk:
break
output += chunk
text = output.decode('ascii', errors='ignore')
if 'Are you sure' in text or 'confirm' in text.lower() or '(y/n)' in text.lower():
client.sendall(b"y\n")
time.sleep(0.08) # 优化:减少确认等待
confirmed = True
output = b""
start = time.time()
continue
if confirmed and ('Please input the file name' in text or 'vrpcfg.zip' in text):
client.sendall(b"\n")
time.sleep(0.08) # 优化:减少等待
file_confirmed = True
output = b""
start = time.time()
continue
if file_confirmed and ('successfully' in text.lower() or 'saved' in text.lower()):
break
if file_confirmed and ('Error' in text or 'error' in text):
break
if file_confirmed and _is_prompt_line(text.strip().split('\n')[-1]) if text.strip() else False:
break
except socket.timeout:
if file_confirmed:
break
if confirmed and not file_confirmed:
client.sendall(b"\n")
time.sleep(0.08)
file_confirmed = True
output = b""
start = time.time()
final_output = output.decode('ascii', errors='ignore')
client.close()
if 'successfully' in final_output.lower() or 'saved' in final_output.lower() or (confirmed and file_confirmed):
logger.info('设备配置保存成功')
return {"status": "success", "msg": "配置已成功保存到设备", "log": final_output}
else:
logger.info(f'设备配置保存完成: {final_output[:200]}')
return {"status": "success", "msg": "保存命令已发送", "log": final_output}
except ConnectionRefusedError:
logger.error(f'连接被拒绝: 端口={port} (尝试 {attempt + 1}/{max_retries})')
if attempt < max_retries - 1:
time.sleep(retry_interval)
continue
else:
return {"status": "error", "msg": "连接被拒绝!请确认 eNSP 中设备已启动(绿色)。"}
except Exception as e:
logger.error(f'保存配置异常: {str(e)} (尝试 {attempt + 1}/{max_retries})')
if attempt < max_retries - 1:
time.sleep(retry_interval)
continue
else:
return {"status": "error", "msg": f"保存配置异常: {str(e)}"}
PARAM_PATTERNS = {
'interface_ip': {
'commands': ['display ip interface brief'],
'parse': lambda lines: _parse_interface_ip(lines),
},
'vlan': {
'commands': ['display vlan'],
'parse': lambda lines: _parse_vlan(lines),
},
'ospf': {
'commands': ['display ospf routing'],
'parse': lambda lines: _parse_ospf(lines),
},
'static_route': {
'commands': ['display ip routing-table'],
'parse': lambda lines: _parse_static_route(lines),
},
'acl': {
'commands': ['display acl configuration'],
'parse': lambda lines: _parse_acl(lines),
},
'vrrp': {
'commands': ['display vrrp'],
'parse': lambda lines: _parse_vrrp(lines),
},
'bgp': {
'commands': ['display bgp routing'],
'parse': lambda lines: _parse_bgp(lines),
},
'rip': {
'commands': ['display rip'],
'parse': lambda lines: _parse_rip(lines),
},
'isis': {
'commands': ['display isis route'],
'parse': lambda lines: _parse_isis(lines),
},
'nat': {
'commands': ['display nat'],
'parse': lambda lines: _parse_nat(lines),
},
'stp': {
'commands': ['display stp'],
'parse': lambda lines: _parse_stp(lines),
},
'eth_trunk': {
'commands': ['display eth-trunk'],
'parse': lambda lines: _parse_eth_trunk(lines),
},
'dhcp': {
'commands': ['display ip pool'],
'parse': lambda lines: _parse_dhcp(lines),
},
'virtual_interface': {
'commands': ['display vlanif'],
'parse': lambda lines: _parse_virtual_interface(lines),
},
'wlan': {
'commands': ['display wlan'],
'parse': lambda lines: _parse_wlan(lines),
},
}
def _parse_interface_ip(lines):
params = {}
intf_pattern = re.compile(r'(GigabitEthernet|Ethernet|Serial|Loopback|Vlanif|Tunnel|MEth)(\S+)')
ip_pattern = re.compile(r'(\d+\.\d+\.\d+\.\d+)\s+(\d+\.\d+\.\d+\.\d+)')
for line in lines:
m = intf_pattern.search(line)
if m:
if 'intf_name' not in params:
params['intf_name'] = m.group(1) + m.group(2)
break