Repository navigation
Expand file tree
/
Copy pathNetOpsBox.psm1
More file actions
2622 lines (2422 loc) · 106 KB
/
Copy pathNetOpsBox.psm1
File metadata and controls
2622 lines (2422 loc) · 106 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
# NetOpsBox.psm1 — 网络运维工具箱主模块
# 版本: 1.0 (Phase 1 骨架)
# 运行环境: Windows PowerShell 5.1
# 编码: UTF-8 with BOM
# ============================================================
# [1] 模块级初始化
# ============================================================
# -- 环境探测 --
$_EnvInfo = @{
OSVersion = [Environment]::OSVersion
Is64BitOS = [Environment]::Is64BitOperatingSystem
Is64BitPS = [Environment]::Is64BitProcess
PSVersion = $PSVersionTable.PSVersion.ToString()
ComputerName = $env:COMPUTERNAME
}
# -- OUI 厂商映射表(约 80 条)--
$_OuiTable = @{
# Cisco
"00000C" = "Cisco"
"00107B" = "Cisco"
"0010F6" = "Cisco"
"0011BB" = "Cisco"
"0011BC" = "Cisco"
"00121A" = "Cisco"
"00127F" = "Cisco"
"0013C4" = "Cisco"
"0016C8" = "Cisco"
"0019E8" = "Cisco"
"001A2F" = "Cisco"
"001AA1" = "Cisco"
"002255" = "Cisco"
"0023EB" = "Cisco"
"0024F7" = "Cisco"
"005080" = "Cisco"
"00E016" = "Cisco"
# Huawei
"00000E" = "Huawei"
"001882" = "Huawei"
"00259C" = "Huawei"
"0025A0" = "Huawei"
"0026B8" = "Huawei"
"085700" = "Huawei"
"1057CA" = "Huawei"
"2021A5" = "Huawei"
# HPE / Aruba
"0001E6" = "HPE/Aruba"
"0004E2" = "HPE/Aruba"
"0017A4" = "HPE/Aruba"
"001871" = "HPE/Aruba"
"001C2E" = "HPE/Aruba"
"0021F7" = "HPE/Aruba"
"009C02" = "HPE/Aruba"
"04BD88" = "Aruba"
"20A6CD" = "Aruba"
# Juniper
"0005A0" = "Juniper"
"00075A" = "Juniper"
"0010DB" = "Juniper"
"0019E4" = "Juniper"
"00237D" = "Juniper"
# Dell
"00016C" = "Dell"
"0007E9" = "Dell"
"001018" = "Dell"
"001422" = "Dell"
"0015C5" = "Dell"
"0023AE" = "Dell"
"F0D5BF" = "Dell"
# Intel
"00001A" = "Intel"
"0002B3" = "Intel"
"0013E8" = "Intel"
"00166F" = "Intel"
"001B21" = "Intel"
"0024D6" = "Intel"
"A4C3F0" = "Intel"
# Realtek
"000085" = "Realtek"
"00095B" = "Realtek"
"001A6B" = "Realtek"
"00238B" = "Realtek"
"D85DEF" = "Realtek"
"E8D8D1" = "Realtek"
# Broadcom
"000017" = "Broadcom"
"0001EA" = "Broadcom"
"0015F2" = "Broadcom"
"00146C" = "Broadcom"
"001BFC" = "Broadcom"
"DCA6BD" = "Broadcom"
# Apple
"000393" = "Apple"
"000A27" = "Apple"
"0010FA" = "Apple"
"001124" = "Apple"
"001451" = "Apple"
"0016CB" = "Apple"
"001E52" = "Apple"
"002312" = "Apple"
"002436" = "Apple"
"00254B" = "Apple"
# Samsung
"0000F0" = "Samsung"
"00016B" = "Samsung"
"0013D3" = "Samsung"
"0017D5" = "Samsung"
"0024E9" = "Samsung"
"18AF61" = "Samsung"
# Xiaomi
"000A9F" = "Xiaomi"
"1038B9" = "Xiaomi"
"28E02C" = "Xiaomi"
"34A84F" = "Xiaomi"
"640980" = "Xiaomi"
"8C6D50" = "Xiaomi"
# TP-Link
"000569" = "TP-Link"
"000625" = "TP-Link"
"001625" = "TP-Link"
"002719" = "TP-Link"
"10683F" = "TP-Link"
"B0487A" = "TP-Link"
# Netgear
"000FB5" = "Netgear"
"0017C2" = "Netgear"
"001B2F" = "Netgear"
"0023A7" = "Netgear"
"08BD43" = "Netgear"
# D-Link
"00055D" = "D-Link"
"000D88" = "D-Link"
"001195" = "D-Link"
"001346" = "D-Link"
"001CF0" = "D-Link"
"0022B0" = "D-Link"
# ASUS
"000C6E" = "ASUS"
"001E8C" = "ASUS"
"002354" = "ASUS"
"08606E" = "ASUS"
# Lenovo
"000103" = "Lenovo"
"0013C6" = "Lenovo"
"0017A8" = "Lenovo"
"00215C" = "Lenovo"
"0024B2" = "Lenovo"
# Microsoft
"0003FF" = "Microsoft"
"00125A" = "Microsoft"
"0017FA" = "Microsoft"
"0022B7" = "Microsoft"
"0050F2" = "Microsoft"
# Google
"001A11" = "Google"
"002590" = "Google"
"3C5AB4" = "Google"
"54A51C" = "Google"
# Ubiquiti
"0004F2" = "Ubiquiti"
"00236A" = "Ubiquiti"
"04A2E2" = "Ubiquiti"
"788A20" = "Ubiquiti"
# Fortinet
"00090F" = "Fortinet"
"001CDF" = "Fortinet"
"00219B" = "Fortinet"
"08A95A" = "Fortinet"
# Palo Alto
"0018CA" = "Palo Alto"
"0022B9" = "Palo Alto"
"008FA1" = "Palo Alto"
# Synology
"001132" = "Synology"
"001DAA" = "Synology"
# H3C
"000FE2" = "H3C"
"0023B8" = "H3C"
"3822D6" = "H3C"
# ZTE
"001E73" = "ZTE"
"0022DE" = "ZTE"
"0024D2" = "ZTE"
# VMware
"000C29" = "VMware"
"005056" = "VMware"
# Other common
"000039" = "Oracle"
"0007CB" = "NVIDIA"
"0008C7" = "IBM"
"00095C" = "Foxconn"
"000E1E" = "Ruckus"
"000D65" = "WatchGuard"
"00116E" = "Check Point"
"00132D" = "F5 Networks"
"0015C7" = "Citrix"
"00178B" = "Extreme"
"001D45" = "Motorola"
"0021A3" = "SonicWall"
}
# -- 知名端口映射表 --
$_WellKnownPorts = @{
21 = "FTP"
22 = "SSH"
23 = "Telnet"
25 = "SMTP"
53 = "DNS"
80 = "HTTP"
443 = "HTTPS"
1433 = "MSSQL"
3306 = "MySQL"
3389 = "RDP"
5432 = "PostgreSQL"
6379 = "Redis"
8080 = "HTTP-Alt"
8443 = "HTTPS-Alt"
27017= "MongoDB"
}
# -- 双语关键字 --
$_BilingualKeywords = @{
RequestTimeout = @("请求超时", "Request timed out")
DestinationUnreachable= @("无法访问目标主机", "Destination host unreachable", "Destination net unreachable")
TtlExpired = @("TTL 传输中过期", "TTL expired in transit")
ReplyFrom = @("来自", "Reply from")
PingStatistics = @("Ping 统计信息", "Ping statistics")
PacketsSent = @("已发送", "Sent")
PacketsReceived = @("已接收", "Received")
PacketsLost = @("丢失", "Lost")
ApproximateRoundTrip = @("往返行程的估计时间", "Approximate round trip")
Minimum = @("最短", "Minimum")
Maximum = @("最长", "Maximum")
Average = @("平均", "Average")
DupReply = @("(DUP!)", "重复应答")
TraceComplete = @("跟踪完成", "Trace complete")
UnableToResolve = @("无法解析目标系统名称", "Unable to resolve target system name")
}
# -- 规模保护阈值 --
$_ScaleThresholds = @{
LanScanAutoMax = 254
LanScanConfirmMax = 4094
BatchPingConfirmMin = 100
DefaultParallelMax = 64
}
# -- 常用命令速查表 --
$_QuickReference = @(
@{ Category = "网络配置"; Command = "ipconfig /all"; Description = "查看完整网络配置" }
@{ Category = "网络配置"; Command = "ipconfig /release"; Description = "释放 DHCP 地址" }
@{ Category = "网络配置"; Command = "ipconfig /renew"; Description = "续租 DHCP 地址" }
@{ Category = "网络配置"; Command = "ipconfig /flushdns"; Description = "清空本地 DNS 缓存" }
@{ Category = "连通性"; Command = "ping -t <目标>"; Description = "持续 Ping" }
@{ Category = "连通性"; Command = "pathping <目标>"; Description = "路径质量分析" }
@{ Category = "端口/进程"; Command = "netstat -ano"; Description = "查看所有连接及监听端口对应 PID" }
@{ Category = "端口/进程"; Command = "taskkill /PID <PID> /F"; Description = "强制结束指定进程" }
@{ Category = "路由/ARP"; Command = "route add <目标> mask <掩码> <网关>"; Description = "添加静态路由" }
@{ Category = "路由/ARP"; Command = "route delete <目标>"; Description = "删除路由条目" }
@{ Category = "路由/ARP"; Command = "arp -d <IP>"; Description = "删除指定 ARP 缓存条目" }
@{ Category = "DNS"; Command = "nslookup <域名> <DNS服务器>"; Description = "指定服务器查询域名" }
@{ Category = "无线网络"; Command = "netsh wlan show profiles"; Description = "列出已保存的 Wi-Fi 配置文件" }
@{ Category = "无线网络"; Command = 'netsh wlan show profile name="<SSID>" key=clear'; Description = "查看已保存 Wi-Fi 的明文密码" }
@{ Category = "防火墙"; Command = "netsh advfirewall show allprofiles"; Description = "查看防火墙各 Profile 状态" }
@{ Category = "共享/权限"; Command = 'net use \\<IP>\<共享名> /user:<用户名> <密码>'; Description = "建立 SMB 共享连接" }
)
# -- 未知行收集器(双语解析兜底用)--
$_UnknownLines = New-Object System.Collections.ArrayList
# ============================================================
# [2] 通用工具函数
# ============================================================
# -- 带颜色输出 --
function _Write-Color {
param(
[Parameter(Mandatory=$true)]
[string]$Text,
[ConsoleColor]$Color = [ConsoleColor]::White
)
Write-Host $Text -ForegroundColor $Color
}
# -- 统一错误格式 --
function _Write-ErrorMsg {
param(
[string]$Reason,
[string]$Suggestion = ""
)
$msg = "[错误] $Reason"
if ($Suggestion) {
$msg += "。建议:$Suggestion"
}
Write-Host $msg -ForegroundColor Red
}
# -- 对齐表格渲染 --
function _Format-Table {
param(
[Parameter(Mandatory=$true)]
[object[]]$Data,
[string[]]$Columns = $null,
[hashtable]$Colors = @{}
)
if (-not $Data -or $Data.Count -eq 0) { return }
# 确定要显示的列
if (-not $Columns) {
$Columns = $Data[0].PSObject.Properties.Name
}
# 计算每列最大宽度
$colWidths = @{}
foreach ($col in $Columns) {
$maxLen = $col.Length
foreach ($row in $Data) {
$val = if ($row -is [hashtable]) { "$($row[$col])" } else { "$($row.$col)" }
if ($val.Length -gt $maxLen) { $maxLen = $val.Length }
}
# 限制最大列宽为终端宽度的一部分
$termWidth = $Host.UI.RawUI.WindowSize.Width
$maxColWidth = [Math]::Min($maxLen, [Math]::Max(10, ($termWidth - ($Columns.Count * 3)) / $Columns.Count))
$colWidths[$col] = [int]$maxColWidth
}
# 渲染表头分隔线
$separator = ""
foreach ($col in $Columns) {
$separator += "-" * $colWidths[$col] + " "
}
Write-Host $separator.TrimEnd() -ForegroundColor DarkGray
# 渲染表头
$header = ""
foreach ($col in $Columns) {
$header += $col.PadRight($colWidths[$col]) + " "
}
Write-Host $header.TrimEnd() -ForegroundColor DarkGray
# 渲染分隔线
Write-Host $separator.TrimEnd() -ForegroundColor DarkGray
# 渲染数据行
foreach ($row in $Data) {
$line = ""
$color = [ConsoleColor]::White
foreach ($col in $Columns) {
$val = if ($row -is [hashtable]) { "$($row[$col])" } else { "$($row.$col)" }
if ($val.Length -gt $colWidths[$col]) {
# 列宽截断:优先截断中间
$half = [int](($colWidths[$col] - 3) / 2)
$val = $val.Substring(0, $half) + "..." + $val.Substring($val.Length - $half, $half)
}
$line += $val.PadRight($colWidths[$col]) + " "
}
# 根据规则取颜色
if ($Colors.Count -gt 0 -and $row -is [hashtable]) {
foreach ($key in $Colors.Keys) {
if ($row[$key] -match $Colors[$key]) {
$color = [ConsoleColor]::Green; break
}
}
}
Write-Host $line.TrimEnd() -ForegroundColor $color
}
Write-Host $separator.TrimEnd() -ForegroundColor DarkGray
}
# -- 参数解析器 --
function _Parse-Args {
param(
[string]$RawInput,
[hashtable]$ParamDefs
)
# 返回一个 PSObject,包含各参数的默认值和用户填写的值
$result = @{}
foreach ($key in $ParamDefs.Keys) {
$def = $ParamDefs[$key]
$result[$key] = $def.Default
}
if ([string]::IsNullOrWhiteSpace($RawInput)) {
return [PSCustomObject]$result
}
# 将输入分割为 token
# 支持位置参数和命名参数
$tokens = @()
$current = ""
$inQuote = $false
foreach ($ch in $RawInput.ToCharArray()) {
if ($ch -eq '"') {
$inQuote = -not $inQuote
} elseif ($ch -eq ' ' -and -not $inQuote) {
if ($current) { $tokens += $current; $current = "" }
} else {
$current += $ch
}
}
if ($current) { $tokens += $current }
# 收集位置参数的定义
$positionalDefs = @()
foreach ($p in $ParamDefs.GetEnumerator()) {
if ($p.Value.Position -ge 0) {
$positionalDefs += @{ Index = $p.Value.Position; Name = $p.Key }
}
}
$positionalDefs = @($positionalDefs | Sort-Object Index)
# 解析 token
$posIndex = 0
$i = 0
while ($i -lt $tokens.Count) {
$t = $tokens[$i]
$matched = $false
# 检查粘连写法: -c50 形式
if ($t -match '^-([a-zA-Z])(\d+)$') {
$shortName = $Matches[1]
$value = $Matches[2]
foreach ($p in $ParamDefs.GetEnumerator()) {
if ($p.Value.Short -eq $shortName) {
$result[$p.Key] = $value
$matched = $true
break
}
}
if ($matched) { $i++; continue }
}
# 检查命名参数
if ($t -match '^-([a-zA-Z]+)$' -or $t -match '^-([a-zA-Z])$') {
$paramName = $Matches[1]
$found = $false
foreach ($p in $ParamDefs.GetEnumerator()) {
if ($p.Value.Long -eq $paramName -or $p.Value.Short -eq $paramName) {
if ($i + 1 -lt $tokens.Count) {
$next = $tokens[$i + 1]
if ($next -notmatch '^-') {
$result[$p.Key] = $next
$i += 2
$found = $true
break
}
}
# 布尔开关参数(无值视为 $true)
$result[$p.Key] = $true
$i++
$found = $true
break
}
}
if ($found) { continue }
}
# 按位置参数处理
if ($posIndex -lt $positionalDefs.Count) {
$pName = $positionalDefs[$posIndex].Name
$result[$pName] = $t
$posIndex++
}
$i++
}
return [PSCustomObject]$result
}
# -- 等待 Enter 键 --
function _Wait-EnterKey {
Write-Host ""
Write-Host "--- 按 Enter 键返回主菜单 ---" -ForegroundColor DarkGray
Read-Host | Out-Null
}
# -- 降级封装 --
function _Invoke-WithFallback {
param(
[Parameter(Mandatory=$true)]
[string]$FeatureName,
[Parameter(Mandatory=$true)]
[ScriptBlock]$Primary,
[Parameter(Mandatory=$true)]
[ScriptBlock]$Fallback,
[Parameter(Mandatory=$true)]
[ScriptBlock]$OutputFormatter
)
try {
$result = & $Primary
if ($null -ne $result) {
return (& $OutputFormatter $result)
}
} catch { }
try {
Write-Host "($FeatureName 兼容模式)" -ForegroundColor DarkGray
$result = & $Fallback
if ($null -ne $result) {
return (& $OutputFormatter $result)
}
} catch { }
_Write-ErrorMsg "$FeatureName 获取失败,两种方式均不可用 "
return @()
}
# -- 获取默认网关 --
function _Get-DefaultGateway {
# Primary: Get-NetRoute
try {
$route = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction Stop |
Sort-Object RouteMetric |
Select-Object -First 1
if ($route) { return $route.NextHop }
} catch { }
# Fallback: route print
try {
$output = & cmd.exe /c "route print 2>&1"
foreach ($line in $output) {
if ($line -match '^\s*0\.0\.0\.0\s+0\.0\.0\.0\s+(\S+)') {
return $Matches[1]
}
}
} catch { }
return $null
}
# -- 获取活跃子网 --
function _Get-ActiveSubnet {
$adapters = @()
# Primary: Get-NetIPAddress + Get-NetAdapter
try {
$netAdapters = Get-NetAdapter -ErrorAction Stop | Where-Object { $_.Status -eq 'Up' }
foreach ($adapter in $netAdapters) {
$ipInfo = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapter.InterfaceIndex -ErrorAction SilentlyContinue |
Where-Object { $_.PrefixOrigin -ne 'WellKnown' } |
Select-Object -First 1
if (-not $ipInfo) { continue }
$route = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceIndex $adapter.InterfaceIndex -ErrorAction SilentlyContinue |
Sort-Object RouteMetric | Select-Object -First 1
$adapters += [PSCustomObject]@{
InterfaceName = $adapter.Name
InterfaceIndex = $adapter.InterfaceIndex
IP = $ipInfo.IPAddress
SubnetMask = $ipInfo.PrefixLength
Gateway = if ($route) { $route.NextHop } else { "" }
Metric = if ($route) { $route.RouteMetric } else { 9999 }
}
}
if ($adapters.Count -gt 0) {
$adapters = $adapters | Sort-Object Metric
return $adapters[0]
}
} catch { }
# Fallback: ipconfig + WMI
try {
$output = & cmd.exe /c "ipconfig 2>&1"
$currentAdapter = $null
foreach ($line in $output) {
if ($line -match '^\S' -and $line -notmatch '^\s') {
$currentAdapter = $line -replace ':.*$', ''
}
if ($currentAdapter -and $line -match 'IPv4.*:\s*(\S+)') {
$ip = $Matches[1]
$maskLine = $output | Where-Object { $_ -match 'Subnet Mask.*:\s*(\S+)' } | Select-Object -First 1
$gwLine = $output | Where-Object { $_ -match 'Default Gateway.*:\s*(\S+)' } | Select-Object -First 1
$mask = if ($maskLine -and $maskLine -match ':\s*(\S+)') { $Matches[1] } else { "" }
$gw = if ($gwLine -and $gwLine -match ':\s*(\S+)') { $Matches[1] } else { "" }
if ($ip -and $ip -ne '') {
return [PSCustomObject]@{
InterfaceName = $currentAdapter
InterfaceIndex = 0
IP = $ip
SubnetMask = $mask
Gateway = if ($gw -and $gw -ne '') { $gw } else { "" }
Metric = 0
}
}
}
}
} catch { }
return $null
}
# -- 获取网卡信息 --
function _Get-AdapterInfo {
return _Invoke-WithFallback -FeatureName "网卡配置" `
-Primary {
$adapters = Get-NetAdapter -ErrorAction Stop
$result = @()
foreach ($adapter in $adapters) {
$ipInfo = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapter.InterfaceIndex -ErrorAction SilentlyContinue |
Where-Object { $_.PrefixOrigin -ne 'WellKnown' } | Select-Object -First 1
$dnsServers = (Get-DnsClientServerAddress -AddressFamily IPv4 -InterfaceIndex $adapter.InterfaceIndex -ErrorAction SilentlyContinue).ServerAddresses -join ', '
$result += [PSCustomObject]@{
Name = $adapter.Name
Status = $adapter.Status
MacAddress = $adapter.MacAddress
IPv4 = if ($ipInfo) { "$($ipInfo.IPAddress)/$($ipInfo.PrefixLength)" } else { "-" }
SubnetMask = if ($ipInfo) { $ipInfo.PrefixLength } else { "-" }
Gateway = if ($ipInfo) { (_Get-DefaultGateway) } else { "-" }
DnsServers = if ($dnsServers) { $dnsServers } else { "-" }
Speed = if ($adapter.LinkSpeed) { "$([Math]::Round($adapter.LinkSpeed / 1e6)) Mbps" } else { "-" }
}
}
return $result
} `
-Fallback {
$adapters = Get-WmiObject Win32_NetworkAdapter -Filter "NetEnabled=True" -ErrorAction Stop
$configs = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "IPEnabled=True" -ErrorAction Stop
$result = @()
foreach ($adapter in $adapters) {
$config = $configs | Where-Object { $_.Index -eq $adapter.Index } | Select-Object -First 1
$result += [PSCustomObject]@{
Name = $adapter.Name
Status = if ($adapter.NetEnabled) { "Up" } else { "Disconnected" }
MacAddress = $adapter.MACAddress
IPv4 = if ($config -and $config.IPAddress) { $config.IPAddress[0] } else { "-" }
SubnetMask = if ($config -and $config.IPSubnet) { $config.IPSubnet[0] } else { "-" }
Gateway = if ($config -and $config.DefaultIPGateway) { $config.DefaultIPGateway[0] } else { "-" }
DnsServers = if ($config -and $config.DNSServerSearchOrder) { $config.DNSServerSearchOrder -join ', ' } else { "-" }
Speed = if ($adapter.Speed) { "$([Math]::Round($adapter.Speed / 1e6)) Mbps" } else { "-" }
}
}
return $result
} `
-OutputFormatter { param($InputObject) return $InputObject }
}
# -- 获取 ARP 表 --
function _Get-ArpTable {
return _Invoke-WithFallback -FeatureName "ARP 缓存" `
-Primary {
$entries = Get-NetNeighbor -AddressFamily IPv4 -ErrorAction Stop
$result = @()
foreach ($e in $entries) {
if ($e.State -notin @('Reachable','Permanent','Stale','Delay','Probe')) { continue }
$type = if ($e.State -eq 'Permanent') { "静态" } else { "动态" }
$result += [PSCustomObject]@{
InterfaceIP = $e.ifIndex
InternetAddress = $e.IPAddress
PhysicalAddress = $e.LinkLayerAddress
Type = $type
}
}
return $result
} `
-Fallback {
$output = & cmd.exe /c "arp -a 2>&1"
$result = @()
$currentInterface = ""
foreach ($line in $output) {
if ($line -match '^接口:\s*(\S+)') {
$currentInterface = $Matches[1]
continue
}
if ($line -match '^\s*(\d+\.\d+\.\d+\.\d+)\s+([0-9a-fA-F-]{17})\s+(\S+)') {
$type = if ($Matches[3] -eq "static") { "静态" } else { "动态" }
$result += [PSCustomObject]@{
InterfaceIP = $currentInterface
InternetAddress = $Matches[1]
PhysicalAddress = $Matches[2]
Type = $type
}
}
}
return $result
} `
-OutputFormatter { param($InputObject) return $InputObject }
}
# -- 获取路由表 --
function _Get-RouteTable {
return _Invoke-WithFallback -FeatureName "路由表" `
-Primary {
$routes = Get-NetRoute -AddressFamily IPv4 -ErrorAction Stop
$result = @()
foreach ($r in $routes) {
$result += [PSCustomObject]@{
Destination = $r.DestinationPrefix
NextHop = $r.NextHop
Interface = $r.InterfaceAlias
Metric = $r.RouteMetric
}
}
return $result
} `
-Fallback {
$output = & cmd.exe /c "route print 2>&1"
$result = @()
$inIPv4 = $false
foreach ($line in $output) {
if ($line -match '^IPv4 路由表' -or $line -match '^IPv4 Route Table') {
$inIPv4 = $true; continue
}
if ($inIPv4 -and ($line -match '^IPv6' -or $line -match '^永久路由')) {
$inIPv4 = $false; continue
}
if ($inIPv4 -and $line -match '^\s*(\d+\.\d+\.\d+\.\d+)\s+(\d+\.\d+\.\d+\.\d+)\s+(\S+)\s+(\S+)\s+(\d+)') {
$result += [PSCustomObject]@{
Destination = $Matches[1]
NextHop = $Matches[3]
Interface = $Matches[4]
Metric = [int]$Matches[5]
}
}
}
return $result
} `
-OutputFormatter { param($InputObject) return $InputObject }
}
# -- 获取监听端口 --
function _Get-ListeningPorts {
return _Invoke-WithFallback -FeatureName "监听端口" `
-Primary {
$connections = Get-NetTCPConnection -State Listen -ErrorAction Stop
$result = @()
foreach ($c in $connections) {
$procName = "未知"
try {
$proc = Get-Process -Id $c.OwningProcess -ErrorAction Stop
$procName = $proc.ProcessName
} catch { }
$result += [PSCustomObject]@{
LocalAddress = if ($c.LocalAddress -eq '0.0.0.0') { "0.0.0.0 (所有网卡)" }
elseif ($c.LocalAddress -eq '::') { "[::] (IPv6)" }
else { $c.LocalAddress }
Port = $c.LocalPort
Protocol = "TCP"
PID = $c.OwningProcess
ProcessName = $procName
}
}
return $result
} `
-Fallback {
$output = & cmd.exe /c "netstat -ano 2>&1"
$result = @()
foreach ($line in $output) {
# 匹配 LISTENING 行: TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 1234
if ($line -match '^\s*TCP\s+(\S+):(\d+)\s+\S+\s+LISTENING\s+(\d+)') {
$addr = $Matches[1]
$port = [int]$Matches[2]
$pid = [int]$Matches[3]
$procName = "未知"
try { $procName = (Get-Process -Id $pid -ErrorAction Stop).ProcessName } catch { }
$displayAddr = if ($addr -eq '0.0.0.0') { "0.0.0.0 (所有网卡)" }
elseif ($addr -match '^\[') { "$addr (IPv6)" }
else { $addr }
$result += [PSCustomObject]@{
LocalAddress = $displayAddr
Port = $port
Protocol = "TCP"
PID = $pid
ProcessName = $procName
}
}
}
return $result
} `
-OutputFormatter { param($InputObject) return $InputObject }
}
# -- OUI 厂商查询 --
function _Resolve-OUI {
param([string]$MacAddress)
if ([string]::IsNullOrWhiteSpace($MacAddress)) { return $null }
# 归一化:去分隔符,转大写,取前 6 字符
$clean = $MacAddress -replace '[:-]', '' -replace '\.', '' -replace '\s', ''
if ($clean.Length -lt 6) { return $null }
$oui = $clean.Substring(0, 6).ToUpper()
if ($_OuiTable.ContainsKey($oui)) {
return $_OuiTable[$oui]
}
return $null
}
# -- 端口服务名查询 --
function _Resolve-PortName {
param([int]$Port)
if ($_WellKnownPorts.ContainsKey($Port)) {
return $_WellKnownPorts[$Port]
}
return $null
}
# -- 显示子菜单 --
function _Show-SubMenu {
param(
[string]$Title,
[hashtable[]]$Options # @{ Key="1"; Label="..." }
)
Write-Host ""
Write-Host "=== $Title ===" -ForegroundColor DarkGray
Write-Host ""
foreach ($opt in $Options) {
Write-Host " [$($opt.Key)] $($opt.Label)"
}
Write-Host " [B] 返回主菜单"
Write-Host ""
}
# -- 规模保护 --
function _Confirm-LargeScale {
param(
[int]$Count,
[int]$AutoMax,
[int]$ConfirmMax,
[string]$Description
)
if ($Count -le $AutoMax) {
return "Proceed"
}
if ($ConfirmMax -gt 0 -and $Count -gt $ConfirmMax) {
Write-Host "目标数量 ($Count) 超过上限 ($ConfirmMax)。$Description 过多,建议缩小范围后重试。" -ForegroundColor Red
return "Reject"
}
Write-Host "检测到 $Description 数量为 $Count,预计耗时较长。是否继续?(Y/N)" -ForegroundColor Yellow
$answer = Read-Host
if ($answer -eq 'Y' -or $answer -eq 'y') {
return "Proceed"
}
return "Reject"
}
# -- IP 地址与 uint32 互转(网络字节序,位运算安全) --
function _IpToUInt32 {
param([string]$IpStr)
$bytes = ([System.Net.IPAddress]$IpStr).GetAddressBytes()
return ([uint32]$bytes[0] -shl 24) -bor ([uint32]$bytes[1] -shl 16) -bor ([uint32]$bytes[2] -shl 8) -bor [uint32]$bytes[3]
}
function _UInt32ToIp {
param([uint32]$Val)
return "$(($Val -shr 24) -band 0xFF).$(($Val -shr 16) -band 0xFF).$(($Val -shr 8) -band 0xFF).$($Val -band 0xFF)"
}
# -- 并行任务调度器(PS5.1 RunspacePool) --
function _Invoke-Parallel {
param(
[ScriptBlock]$ScriptBlock,
[object[]]$InputObjects,
[int]$Throttle = 20,
[ScriptBlock]$OnComplete = $null
)
if ($InputObjects.Count -eq 0) { return @() }
if ($InputObjects.Count -eq 1) {
$r = & $ScriptBlock $InputObjects[0]
if ($OnComplete) { & $OnComplete $r }
return @($r)
}
$throttle = [Math]::Min($Throttle, $InputObjects.Count)
$pool = [RunspaceFactory]::CreateRunspacePool(1, $throttle)
$pool.Open()
$tasks = New-Object System.Collections.ArrayList
foreach ($obj in $InputObjects) {
$ps = [PowerShell]::Create()
$ps.RunspacePool = $pool
[void]$ps.AddScript($ScriptBlock.ToString())
[void]$ps.AddArgument($obj)
$async = $ps.BeginInvoke()
[void]$tasks.Add(@{ PS=$ps; Async=$async; Obj=$obj })
}
$results = New-Object System.Collections.ArrayList
foreach ($task in $tasks) {
try {
$dataColl = $task.PS.EndInvoke($task.Async)
if ($dataColl -and $dataColl.Count -gt 0) {
$data = $dataColl[0]
if ($null -ne $data) {
[void]$results.Add($data)
if ($OnComplete) { & $OnComplete $data }
}
}
} catch {
if ($OnComplete) { & $OnComplete @{ Error = $_.Exception.Message; Obj = $task.Obj } }
}
$task.PS.Dispose()
}
$pool.Close()
$pool.Dispose()
return $results.ToArray()
}
# -- 通用 E 键退出检测 --
function _Check-ExitKey {
if ([Console]::KeyAvailable) {
$key = [Console]::ReadKey($true)
if ($key.Key -eq 'E') {
Write-Host ""
_Write-Color "[已取消] 用户按 E 键退出" Yellow
return $true
}
}
return $false
}
# -- 双语关键字匹配 --
function _Match-Bilingual {
param(
[Parameter(Mandatory=$true)]
[string]$Line,
[Parameter(Mandatory=$true)]
[string]$Category
)
$keywords = $_BilingualKeywords[$Category]
if (-not $keywords) {
return $false
}
foreach ($kw in $keywords) {
if ($Line -match [regex]::Escape($kw)) {
return $true
}
}
# 记录未知行,供调用方后续处理
[void]$_UnknownLines.Add($Line)
return $false
}
# -- Ping 输出解析器 --
function _Parse-PingOutput {
param(
[Parameter(Mandatory=$true)]
[string[]]$Output
)
$replies = New-Object System.Collections.ArrayList
$stats = @{}
$dupDetected = $false
$dupData = @()
# 已见过的序号(用于检测 DUP!)
$seenSeq = @{}
foreach ($line in $Output) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
# 检测 DUP!
if ($line -match '\(DUP!\)' -or $line -match '重复应答') {
$dupDetected = $true
}
# 解析应答行: "来自 192.168.1.1: 字节=32 时间=1ms TTL=64" 或
# "Reply from 192.168.1.1: bytes=32 time=1ms TTL=64"
if ($line -match '(?:来自|Reply from)\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)[:\s]') {
$ip = $Matches[1]
$ttl = if ($line -match '(?:TTL|ttl)[= ]*([0-9]+)') { [int]$Matches[1] } else { 0 }
$bytes = if ($line -match '(?:字节|bytes)[= ]*([0-9]+)') { [int]$Matches[1] } else { 0 }
$time = if ($line -match '(?:时间|time)[=< ]*([0-9]+)\s*ms') { [int]$Matches[1] } else { 0 }
$isDup = $line -match '\(DUP!\)' -or $line -match '重复应答'
$entry = [PSCustomObject]@{
IP = $ip
TTL = $ttl
Bytes = $bytes
TimeMs = $time
Status = if ($isDup) { "DUP" } else { "Reply" }
}
[void]$replies.Add($entry)
continue
}
# 检测超时行
if (_Match-Bilingual -Line $line -Category "RequestTimeout") {
[void]$replies.Add([PSCustomObject]@{ IP="*"; TTL=0; Bytes=0; TimeMs=0; Status="Timeout" })
continue
}
# 检测不可达行
if (_Match-Bilingual -Line $line -Category "DestinationUnreachable") {
[void]$replies.Add([PSCustomObject]@{ IP="*"; TTL=0; Bytes=0; TimeMs=0; Status="Unreachable" })
continue
}
# 解析统计信息
# 报文统计行(英文/中文均为一行)
if (_Match-Bilingual -Line $line -Category "PacketsSent") {
# English: "Packets: Sent = 3, Received = 3, Lost = 0"
# Chinese: "数据包: 已发送 = 3,已接收 = 3,丢失 = 0"
if ($line -match 'Sent\s*=\s*(\d+)') { $stats['Sent'] = [int]$Matches[1] }
elseif ($line -match '已发送\s*=\s*(\d+)') { $stats['Sent'] = [int]$Matches[1] }
if ($line -match 'Received\s*=\s*(\d+)') { $stats['Received'] = [int]$Matches[1] }
elseif ($line -match '已接收\s*=\s*(\d+)') { $stats['Received'] = [int]$Matches[1] }
if ($line -match 'Lost\s*=\s*(\d+)') { $stats['Lost'] = [int]$Matches[1] }
elseif ($line -match '丢失\s*=\s*(\d+)') { $stats['Lost'] = [int]$Matches[1] }
}
# 延迟统计行
if (_Match-Bilingual -Line $line -Category "Minimum") {