-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-SwitchInfo.ps1
More file actions
1314 lines (1092 loc) · 52.8 KB
/
Get-SwitchInfo.ps1
File metadata and controls
1314 lines (1092 loc) · 52.8 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
<#
.SYNOPSIS
Grab upstream switch information from LLDP and post to Hudu
.DESCRIPTION
Polls network adapters for an active network connection. On success, return the IP address of the upstream switch,
the Port Identifier (typically Port Number) and switch model
.NOTES
Version: 1.0
Author: Alden Wilson
Creation Date: 07-03-2023
Last Update: 07-04-2023
* The error handling on line 34 must be modified to fit your deployment tool (RMM or otherwise)
* Modify the $filepath variable on line 100 to fit company preferences.
TODO: Create helper function to tie into documentation system to properly correlate data with related devices (Endpoints and Switches)
#>
<###########
Classes
############>
class DiscoveryProtocolPacket {
[string]$MachineName
[datetime]$TimeCreated
[int]$FragmentSize
[byte[]]$Fragment
[int]$MiniportIfIndex
[string]$Connection
[string]$Interface
DiscoveryProtocolPacket([PSCustomObject]$WinEvent) {
$this.MachineName = $WinEvent.MachineName
$this.TimeCreated = $WinEvent.TimeCreated
$this.FragmentSize = $WinEvent.FragmentSize
$this.Fragment = $WinEvent.Fragment
$this.MiniportIfIndex = $WinEvent.MiniportIfIndex
$this.Connection = $WinEvent.Connection
$this.Interface = $WinEvent.Interface
Add-Member -InputObject $this -MemberType ScriptProperty -Name IsDiscoveryProtocolPacket -Value {
if (
[UInt16]0x2000 -eq [BitConverter]::ToUInt16($this.Fragment[21..20], 0) -or
[UInt16]0x88CC -eq [BitConverter]::ToUInt16($this.Fragment[13..12], 0)
) { return [bool]$true } else { return [bool]$false }
}
Add-Member -InputObject $this -MemberType ScriptProperty -Name DiscoveryProtocolType -Value {
if ([UInt16]0x2000 -eq [BitConverter]::ToUInt16($this.Fragment[21..20], 0)) {
return [string]'CDP'
}
elseif ([UInt16]0x88CC -eq [BitConverter]::ToUInt16($this.Fragment[13..12], 0)) {
return [string]'LLDP'
}
else {
return [string]::Empty
}
}
Add-Member -InputObject $this -MemberType ScriptProperty -Name SourceAddress -Value {
[PhysicalAddress]::new($this.Fragment[6..11]).ToString()
}
}
}
<############
Functions
############>
function Test-Administrator {
[OutputType([bool])]
param()
process {
[Security.Principal.WindowsPrincipal]$user = [Security.Principal.WindowsIdentity]::GetCurrent();
return $user.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator);
}
}
if (-not (Test-Administrator)) {
# Write proper error handling for your RMM
Write-Host "This script must be ran as Administrator";
exit 1;
}
$ErrorActionPreference = "Stop";
function Invoke-DiscoveryProtocolCapture {
<#
.SYNOPSIS
Capture CDP or LLDP packets on local or remote computers
.DESCRIPTION
Capture discovery protocol packets on local or remote computers. This function will start a packet capture and save the
captured packets in a temporary ETL file. Only the first discovery protocol packet in the ETL file will be returned.
Cisco devices will by default send CDP announcements every 60 seconds. Default interval for LLDP packets is 30 seconds.
Requires elevation (Run as Administrator) for local capture.
WinRM and PowerShell remoting must be enabled on target computer for remote capture.
.PARAMETER ComputerName
Specifies one or more computers on which to capture packets. Defaults to $env:COMPUTERNAME.
If specified, remote capture is assumed and therefore WinRM must be enabled on target.
.PARAMETER Duration
Specifies the duration for which the discovery protocol packets are captured, in seconds.
If Type is LLDP, Duration defaults to 32. If Type is CDP or omitted, Duration defaults to 62.
.PARAMETER Type
Specifies what type of packet to capture, CDP or LLDP. If omitted, both types will be captured,
but only the first one will be returned.
If Type is LLDP, Duration defaults to 32. If Type is CDP or omitted, Duration defaults to 62.
.PARAMETER Credential
Use this with remote capture if current user do not have administrative privileges on the target computer.
.OUTPUTS
DiscoveryProtocolPacket
.EXAMPLE
PS C:\> Invoke-DiscoveryProtocolCapture -Computer COMPUTER1 | Get-DiscoveryProtocolData
Port : FastEthernet0/1
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 10
Computer : COMPUTER1
Type : CDP
.EXAMPLE
PS C:\> 'COMPUTER1', 'COMPUTER2' | Invoke-DiscoveryProtocolCapture | Get-DiscoveryProtocolData
Port : FastEthernet0/1
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 10
Computer : COMPUTER1
Type : CDP
Port : FastEthernet0/2
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 20
Computer : COMPUTER2
Type : CDP
#>
[CmdletBinding(DefaultParametersetName = 'LocalCapture')]
[OutputType('DiscoveryProtocolPacket')]
[Alias('Capture-CDPPacket', 'Capture-LLDPPacket')]
param(
[Parameter(ParameterSetName = 'RemoteCapture',
Mandatory = $false,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[Alias('CN', 'Computer')]
[String[]]$ComputerName = $env:COMPUTERNAME,
[Parameter(ParameterSetName = 'LocalCapture',
Position = 0)]
[Parameter(ParameterSetName = 'RemoteCapture',
Position = 1)]
[Int16]$Duration = $(if ($Type -eq 'LLDP') { 32 } else { 62 }),
[Parameter(ParameterSetName = 'LocalCapture',
Position = 1)]
[Parameter(ParameterSetName = 'RemoteCapture',
Position = 2)]
[ValidateSet('CDP', 'LLDP')]
[String]$Type,
[Parameter(ParameterSetName = 'RemoteCapture')]
[ValidateNotNull()]
[System.Management.Automation.Credential()]
[PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty,
[Parameter()]
[switch]$NoCleanup,
[Parameter()]
[switch]$Force
)
begin {
if ($PSCmdlet.ParameterSetName -eq 'LocalCapture') {
$Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$Principal = New-Object Security.Principal.WindowsPrincipal $Identity
if (-not $Principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
throw 'Invoke-DiscoveryProtocolCapture requires elevation. Please run PowerShell as administrator.'
}
}
if ($MyInvocation.InvocationName -ne $MyInvocation.MyCommand) {
if ($MyInvocation.InvocationName -eq 'Capture-CDPPacket') { $Type = 'CDP' }
if ($MyInvocation.InvocationName -eq 'Capture-LLDPPacket') { $Type = 'LLDP' }
$Warning = '{0} has been deprecated, please use {1}' -f $MyInvocation.InvocationName, $MyInvocation.MyCommand
Write-Warning $Warning
}
}
process {
foreach ($Computer in $ComputerName) {
Write-Verbose "ParameterSetName: $($PSCmdlet.ParameterSetName)"
Write-Verbose "TargetComputer: $Computer"
if ($PSCmdlet.ParameterSetName -eq 'LocalCapture') {
$CimSession = @{}
$PSSession = @{}
}
else {
$PSCredential = @{}
if ($PSBoundParameters.ContainsKey('Credential')) {
$PSCredential.Add('Credential', $Credential)
}
try {
$CimSession = @{
CimSession = New-CimSession -ComputerName $Computer -ErrorAction Stop @PSCredential
}
}
catch [Microsoft.Management.Infrastructure.CimException] {
if ($_.CategoryInfo.Category -eq 'PermissionDenied') {
Write-Warning "Access Denied on $Computer. You can try to connect using -Credential."
}
elseif ($_.CategoryInfo.Category -eq 'ConnectionError') {
Write-Warning "Unable to create CimSession. Please make sure WinRM and PSRemoting is enabled on $Computer."
}
else {
Write-Error -ErrorRecord $_
}
continue
}
catch {
Write-Error -ErrorRecord $_
continue
}
try {
$PSSession = @{
Session = New-PSSession -ComputerName $Computer -ErrorAction Stop @PSCredential
}
}
catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
if ($_.Exception.ErrorCode -eq 5) {
Write-Warning "Access Denied on $Computer. You can try to connect using -Credential."
}
elseif ($_.Exception.ErrorCode -eq -2144108526) {
Write-Warning "Unable to create CimSession. Please make sure WinRM and PSRemoting is enabled on $Computer."
}
else {
Write-Error -ErrorRecord $_
}
continue
}
catch {
Write-Error -ErrorRecord $_
continue
}
}
$ETLFilePath = Invoke-Command @PSSession -ScriptBlock {
$TempFile = New-TemporaryFile
$ETLFile = Rename-Item -Path $TempFile.FullName -NewName $TempFile.FullName.Replace('.tmp', '.etl') -PassThru
$ETLFile.FullName
}
Write-Verbose "ETLFilePath: $ETLFilePath"
$Adapters = Get-NetAdapter @CimSession |
Where-Object { $_.Status -eq 'Up' -and $_.InterfaceType -eq 6 } |
Select-Object Name, MacAddress, InterfaceDescription, InterfaceIndex
if ($Adapters) {
$MACAddresses = $Adapters.MacAddress.ForEach({ [PhysicalAddress]::Parse($_).ToString() })
$SessionName = 'Capture-{0}' -f (Get-Date).ToString('s')
if ($Force.IsPresent) {
Get-NetEventSession @CimSession | ForEach-Object {
if ($_.SessionStatus -eq 'Running') {
$_ | Stop-NetEventSession @CimSession
}
$_ | Remove-NetEventSession @CimSession
}
}
try {
New-NetEventSession -Name $SessionName -LocalFilePath $ETLFilePath -CaptureMode SaveToFile @CimSession -ErrorAction Stop | Out-Null
}
catch [Microsoft.Management.Infrastructure.CimException] {
if ($_.Exception.NativeErrorCode -eq 'AlreadyExists') {
$Message = "Another NetEventSession already exists. Run Invoke-DiscoveryProtocolCapture with -Force switch to remove existing NetEventSessions."
Write-Error -Message $Message
}
else {
Write-Error -ErrorRecord $_
}
continue
}
$LinkLayerAddress = switch ($Type) {
'CDP' { '01-00-0c-cc-cc-cc' }
'LLDP' { '01-80-c2-00-00-0e', '01-80-c2-00-00-03', '01-80-c2-00-00-00' }
Default { '01-00-0c-cc-cc-cc', '01-80-c2-00-00-0e', '01-80-c2-00-00-03', '01-80-c2-00-00-00' }
}
$PacketCaptureParams = @{
SessionName = $SessionName
TruncationLength = 0
CaptureType = 'Physical'
LinkLayerAddress = $LinkLayerAddress
}
Add-NetEventPacketCaptureProvider @PacketCaptureParams @CimSession | Out-Null
foreach ($Adapter in $Adapters) {
Add-NetEventNetworkAdapter -Name $Adapter.Name -PromiscuousMode $True @CimSession | Out-Null
}
Start-NetEventSession -Name $SessionName @CimSession
$Seconds = $Duration
$End = (Get-Date).AddSeconds($Seconds)
while ($End -gt (Get-Date)) {
$SecondsLeft = $End.Subtract((Get-Date)).TotalSeconds
$Percent = ($Seconds - $SecondsLeft) / $Seconds * 100
Write-Progress -Activity "Discovery Protocol Packet Capture" -Status "Capturing on $Computer..." -SecondsRemaining $SecondsLeft -PercentComplete $Percent
[System.Threading.Thread]::Sleep(500)
}
Stop-NetEventSession -Name $SessionName @CimSession
$Events = Invoke-Command @PSSession -ScriptBlock {
param(
$ETLFilePath
)
try {
$Events = Get-WinEvent -Path $ETLFilePath -Oldest -FilterXPath "*[System[EventID=1001]]" -ErrorAction Stop
}
catch {
if ($_.FullyQualifiedErrorId -notmatch 'NoMatchingEventsFound') {
Write-Error -ErrorRecord $_
}
}
[string[]]$XpathQueries = @(
"Event/EventData/Data[@Name='FragmentSize']"
"Event/EventData/Data[@Name='Fragment']"
"Event/EventData/Data[@Name='MiniportIfIndex']"
)
$PropertySelector = [System.Diagnostics.Eventing.Reader.EventLogPropertySelector]::new($XpathQueries)
foreach ($WinEvent in $Events) {
$EventData = $WinEvent | Select-Object MachineName, TimeCreated
$EventData | Add-Member -NotePropertyName FragmentSize -NotePropertyValue $null
$EventData | Add-Member -NotePropertyName Fragment -NotePropertyValue $null
$EventData | Add-Member -NotePropertyName MiniportIfIndex -NotePropertyValue $null
$EventData.FragmentSize, $EventData.Fragment, $EventData.MiniportIfIndex = $WinEvent.GetPropertyValues($PropertySelector)
$Adapter = @(Get-NetAdapter).Where({ $_.InterfaceIndex -eq $EventData.MiniportIfIndex })
$EventData | Add-Member -NotePropertyName Connection -NotePropertyValue $Adapter.Name
$EventData | Add-Member -NotePropertyName Interface -NotePropertyValue $Adapter.InterfaceDescription
$EventData
}
} -ArgumentList $ETLFilePath
$FoundPackets = $Events -as [DiscoveryProtocolPacket[]] | Where-Object {
$_.IsDiscoveryProtocolPacket -and $_.SourceAddress -notin $MACAddresses
} | Group-Object MiniportIfIndex | ForEach-Object {
$_.Group | Select-Object -First 1
}
Remove-NetEventSession -Name $SessionName @CimSession
if (-not $NoCleanup.IsPresent) {
Invoke-Command @PSSession -ScriptBlock {
param(
$ETLFilePath
)
Remove-Item -Path $ETLFilePath -Force
} -ArgumentList $ETLFilePath
}
if ($PSCmdlet.ParameterSetName -eq 'RemoteCapture') {
Remove-PSSession @PSSession
Remove-CimSession @CimSession
}
if ($FoundPackets) {
$FoundPackets
}
else {
Write-Warning "No discovery protocol packets captured on $Computer in $Seconds seconds."
return
}
}
else {
Write-Warning "Unable to find a connected wired adapter on $Computer."
return
}
}
}
end {}
}
function Get-DiscoveryProtocolData {
<#
.SYNOPSIS
Parse CDP or LLDP packets captured by Invoke-DiscoveryProtocolCapture
.DESCRIPTION
Gets computername, type and packet details from a DiscoveryProtocolPacket.
Calls ConvertFrom-CDPPacket or ConvertFrom-LLDPPacket to extract packet details
from a byte array.
.PARAMETER Packet
Specifies an object of type DiscoveryProtocolPacket.
.EXAMPLE
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture
PS C:\> Get-DiscoveryProtocolData -Packet $Packet
Port : FastEthernet0/1
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 10
Computer : COMPUTER1
Type : CDP
.EXAMPLE
PS C:\> Invoke-DiscoveryProtocolCapture -Computer COMPUTER1 | Get-DiscoveryProtocolData
Port : FastEthernet0/1
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 10
Computer : COMPUTER1
Type : CDP
.EXAMPLE
PS C:\> 'COMPUTER1', 'COMPUTER2' | Invoke-DiscoveryProtocolCapture | Get-DiscoveryProtocolData
Port : FastEthernet0/1
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 10
Computer : COMPUTER1
Type : CDP
Port : FastEthernet0/2
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 20
Computer : COMPUTER2
Type : CDP
#>
[CmdletBinding()]
[Alias('Parse-CDPPacket', 'Parse-LLDPPacket')]
param(
[Parameter(Position = 0,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[DiscoveryProtocolPacket[]]
$Packet
)
begin {
if ($MyInvocation.InvocationName -ne $MyInvocation.MyCommand) {
$Warning = '{0} has been deprecated, please use {1}' -f $MyInvocation.InvocationName, $MyInvocation.MyCommand
Write-Warning $Warning
}
}
process {
foreach ($Item in $Packet) {
switch ($Item.DiscoveryProtocolType) {
'CDP' { $PacketData = ConvertFrom-CDPPacket -Packet $Item.Fragment }
'LLDP' { $PacketData = ConvertFrom-LLDPPacket -Packet $Item.Fragment }
Default { throw 'No valid CDP or LLDP found in $Packet' }
}
$PacketData | Add-Member -NotePropertyName Computer -NotePropertyValue $Item.MachineName
$PacketData | Add-Member -NotePropertyName Connection -NotePropertyValue $Item.Connection
$PacketData | Add-Member -NotePropertyName Interface -NotePropertyValue $Item.Interface
$PacketData | Add-Member -NotePropertyName Type -NotePropertyValue $Item.DiscoveryProtocolType
$PacketData
}
}
end {}
}
function ConvertFrom-CDPPacket {
<#
.SYNOPSIS
Parse CDP packet.
.DESCRIPTION
Parse CDP packet to get port, device, model, ipaddress and vlan.
This function is used by Get-DiscoveryProtocolData to parse the
Fragment property of a DiscoveryProtocolPacket object.
.PARAMETER Packet
Raw CDP packet as byte array.
This function is used by Get-DiscoveryProtocolData to parse the
Fragment property of a DiscoveryProtocolPacket object.
.EXAMPLE
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture -Type CDP
PS C:\> ConvertFrom-CDPPacket -Packet $Packet.Fragment
Port : FastEthernet0/1
Device : SWITCH1.domain.example
Model : cisco WS-C2960-48TT-L
IPAddress : 192.0.2.10
VLAN : 10
#>
[CmdletBinding()]
param(
[Parameter(Position = 0,
Mandatory = $true)]
[byte[]]$Packet
)
$Stream = New-Object System.IO.MemoryStream (, $Packet)
$Reader = New-Object System.IO.BinaryReader $Stream
$Destination = [PhysicalAddress]$Reader.ReadBytes(6)
$Source = [PhysicalAddress]$Reader.ReadBytes(6)
$Length = [System.BitConverter]::ToUInt16($Reader.ReadBytes(2)[1..0], 0)
$null = $Reader.ReadBytes(6)
$CDP = [System.BitConverter]::ToString($Reader.ReadBytes(2))
$Version = $Reader.ReadByte()
$TimeToLive = $Reader.ReadByte()
$null = $Reader.ReadBytes(2)
$Tlv = @{
0x0001 = 'Device'
0x0002 = 'IPAddress'
0x0003 = 'Port'
0x0006 = 'Model'
0x000A = 'VLAN'
0x0016 = 'Management'
}
$TypeString = 0x0001, 0x003, 0x006
$TypeAddress = 0x0002, 0x0016
$TypeInt = 0x000A
$IPv4 = 0xCC
$IPv6 = 0xAAAA0300000086DD
$Properties = @{}
Write-Verbose "Destination : $Destination"
Write-Verbose "Source : $Source"
Write-Verbose "Length : $Length"
Write-Verbose "Protocol ID : $CDP"
Write-Verbose "CDP Version : $Version"
Write-Verbose "Time To Live : $TimeToLive seconds"
Write-Verbose "----------------------------------------------------------------"
while ($Reader.PeekChar() -ne -1) {
$TlvType = [System.BitConverter]::ToUInt16($Reader.ReadBytes(2)[1..0], 0)
$TlvLength = [System.BitConverter]::ToUInt16($Reader.ReadBytes(2)[1..0], 0)
switch ($TlvType) {
{ $_ -in $TypeString } {
$String = $Reader.ReadChars($TlvLength - 4) -join ''
$Properties.Add($Tlv.Item([int]$TlvType), $String)
}
{ $_ -in $TypeAddress } {
$NumberOfAddresses = [System.BitConverter]::ToUInt32($Reader.ReadBytes(4)[3..0], 0)
$Addresses = New-Object System.Collections.Generic.List[String]
if ($NumberOfAddresses -gt 0) {
1..$NumberOfAddresses | ForEach-Object {
$ProtocolType = $Reader.ReadByte()
$ProtocolLength = $Reader.ReadByte()
if ($ProtocolLength -eq 1) {
$Protocol = $Reader.ReadByte()
}
else {
$Protocol = [System.BitConverter]::ToInt64($Reader.ReadBytes(8)[7..0], 0)
}
$AddressLength = [System.BitConverter]::ToUInt16($Reader.ReadBytes(2)[1..0], 0)
$AddressBytes = $Reader.ReadBytes($AddressLength)
if (($ProtocolType -eq 0x01 -and $Protocol -eq $IPv4) -or ($ProtocolType -eq 0x02 -and $Protocol -eq $IPv6)) {
$IPAddress = [System.Net.IPAddress]::new($AddressBytes).IPAddressToString
$Addresses.Add($IPAddress)
}
else {
$ProtocolBytes = [System.BitConverter]::GetBytes($Protocol)[7..0]
$ProtocolHex = [System.BitConverter]::ToString($ProtocolBytes)
$AddressHex = [System.BitConverter]::ToString($AddressBytes)
Write-Verbose "TlvType : $TlvType"
Write-Verbose "TlvLength : $TlvLength"
Write-Verbose "ProtocolType : $ProtocolType"
Write-Verbose "ProtocolLength : $ProtocolLength"
Write-Verbose "ProtocolHex : $ProtocolHex"
Write-Verbose "AddressLength : $AddressLength"
Write-Verbose "AddressHex : $AddressHex"
Write-Verbose "----------------------------------------------------------------"
}
}
}
else {
Write-Verbose "TlvType : $TlvType"
Write-Verbose "TlvLength : $TlvLength"
Write-Verbose "NumOfAddresses : $NumberOfAddresses"
Write-Verbose "----------------------------------------------------------------"
}
if ($Addresses.Count -gt 0) {
$Properties.Add($Tlv.Item([int]$TlvType), $Addresses)
}
}
$TypeInt {
$NativeVlan = [System.BitConverter]::ToUInt16($Reader.ReadBytes(2)[1..0], 0)
$Properties.Add($Tlv.Item([int]$TlvType), $NativeVlan)
}
default {
$Bytes = $Reader.ReadBytes($TlvLength - 4)
$Chars = $Bytes -as [System.Char[]]
$Hex = [System.BitConverter]::ToString($Bytes)
$Ascii = $Chars -join ''
Write-Verbose "TlvType : $TlvType"
Write-Verbose "TlvLength : $TlvLength"
Write-Verbose "Hex : $Hex"
Write-Verbose "Ascii : $Ascii"
Write-Verbose "----------------------------------------------------------------"
}
}
}
New-Object PSObject -Property $Properties
}
function ConvertFrom-LLDPPacket {
<#
.SYNOPSIS
Parse LLDP packet.
.DESCRIPTION
Parse LLDP packet to get port, description, device, model, ipaddress and vlan.
.PARAMETER Packet
Raw LLDP packet as byte array.
This function is used by Get-DiscoveryProtocolData to parse the
Fragment property of a DiscoveryProtocolPacket object.
.EXAMPLE
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture -Type LLDP
PS C:\> ConvertFrom-LLDPPacket -Packet $Packet.Fragment
Model : WS-C2960-48TT-L
Description : HR Workstation
VLAN : 10
Port : Fa0/1
Device : SWITCH1.domain.example
IPAddress : 192.0.2.10
#>
[CmdletBinding()]
param(
[Parameter(Position = 0,
Mandatory = $true)]
[byte[]]$Packet
)
begin {
$TlvType = @{
EndOfLLDPDU = 0
ChassisId = 1
PortId = 2
TimeToLive = 3
PortDescription = 4
SystemName = 5
SystemDescription = 6
ManagementAddress = 8
OrganizationSpecific = 127
}
}
process {
$Destination = [PhysicalAddress]::new($Packet[0..5])
$Source = [PhysicalAddress]::new($Packet[6..11])
$EtherType = [BitConverter]::ToString($Packet[12..13])
Write-Verbose "Destination : $Destination"
Write-Verbose "Source : $Source"
Write-Verbose "EtherType : $EtherType"
Write-Verbose "----------------------------------------------------------------"
$Offset = 14
$Mask = 0x01FF
$Hash = @{}
while ($Offset -lt $Packet.Length) {
$Type = $Packet[$Offset] -shr 1
$Length = [BitConverter]::ToUInt16($Packet[($Offset + 1)..$Offset], 0) -band $Mask
$Offset += 2
switch ($Type) {
$TlvType.ChassisId {
$Subtype = $Packet[($Offset)]
if ($SubType -in (1, 2, 3, 6, 7)) {
$Hash.Add('ChassisId', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 1)..($Offset + $Length - 1)]))
}
if ($Subtype -eq 5) {
$AddressFamily = $Packet[($Offset + 1)]
if ($AddressFamily -in 1, 2) {
$Hash.Add('ChassisId', [IPAddress]::new($Packet[($Offset + 2)..($Offset + $Length - 1)]))
}
else {
$Bytes = $Packet[($Offset + 2)..($Offset + $Length - 1)]
$Hex = [System.BitConverter]::ToString($Bytes)
$Ascii = [System.Text.Encoding]::ASCII.GetString($Bytes)
Write-Verbose "TlvType : $Type"
Write-Verbose "TlvLength : $Length"
write-Verbose "SubType : $Subtype"
Write-Verbose "AddressFamily : $AddressFamily"
Write-Verbose "Hex : $Hex"
Write-Verbose "Ascii : $Ascii"
Write-Verbose "----------------------------------------------------------------"
}
}
if ($Subtype -eq 4) {
$Hash.Add('ChassisId', [PhysicalAddress]::new($Packet[($Offset + 1)..($Offset + $Length - 1)]))
}
$Offset += $Length
break
}
$TlvType.PortId {
$Subtype = $Packet[($Offset)]
if ($SubType -in (1, 2, 5, 6, 7)) {
$Hash.Add('Port', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 1)..($Offset + $Length - 1)]))
}
if ($Subtype -eq 4) {
$AddressFamily = $Packet[($Offset + 1)]
if ($AddressFamily -in 1, 2) {
$Hash.Add('Port', [IPAddress]::new($Packet[($Offset + 2)..($Offset + $Length - 1)]))
}
else {
$Bytes = $Packet[($Offset + 2)..($Offset + $Length - 1)]
$Hex = [System.BitConverter]::ToString($Bytes)
$Ascii = [System.Text.Encoding]::ASCII.GetString($Bytes)
Write-Verbose "TlvType : $Type"
Write-Verbose "TlvLength : $Length"
write-Verbose "SubType : $Subtype"
Write-Verbose "AddressFamily : $AddressFamily"
Write-Verbose "Hex : $Hex"
Write-Verbose "Ascii : $Ascii"
Write-Verbose "----------------------------------------------------------------"
}
}
if ($Subtype -eq 3) {
$Hash.Add('Port', [PhysicalAddress]::new($Packet[($Offset + 1)..($Offset + $Length - 1)]))
}
$Offset += $Length
break
}
$TlvType.TimeToLive {
$Hash.Add('TimeToLive', [BitConverter]::ToUInt16($Packet[($Offset + 1)..$Offset], 0))
$Offset += $Length
break
}
$TlvType.PortDescription {
$Hash.Add('PortDescription', [System.Text.Encoding]::ASCII.GetString($Packet[$Offset..($Offset + $Length - 1)]))
$Offset += $Length
break
}
$TlvType.SystemName {
$Hash.Add('Device', [System.Text.Encoding]::ASCII.GetString($Packet[$Offset..($Offset + $Length - 1)]))
$Offset += $Length
break
}
$TlvType.SystemDescription {
$Hash.Add('SystemDescription', [System.Text.Encoding]::ASCII.GetString($Packet[$Offset..($Offset + $Length - 1)]))
$Offset += $Length
break
}
$TlvType.ManagementAddress {
$AddrLen = $Packet[($Offset)]
$Subtype = $Packet[($Offset + 1)]
if (-not $Hash.ContainsKey('IPAddress') -and $Subtype -in 1, 2) {
$Addresses = New-Object System.Collections.Generic.List[String]
$Hash.Add('IPAddress', $Addresses)
}
if ($Subtype -in 1, 2) {
$Addresses.Add(([System.Net.IPAddress][byte[]]$Packet[($Offset + 2)..($Offset + $AddrLen)]).IPAddressToString)
}
else {
$Bytes = $Packet[($Offset + 2)..($Offset + $AddrLen)]
$Hex = [System.BitConverter]::ToString($Bytes)
$Ascii = [System.Text.Encoding]::ASCII.GetString($Bytes)
Write-Verbose "TlvType : $Type"
Write-Verbose "TlvLength : $Length"
Write-Verbose "AddressLength : $AddrLen"
write-Verbose "SubType : $Subtype"
Write-Verbose "Hex : $Hex"
Write-Verbose "Ascii : $Ascii"
Write-Verbose "----------------------------------------------------------------"
}
$Offset += $Length
break
}
$TlvType.OrganizationSpecific {
$OUI = [System.BitConverter]::ToString($Packet[($Offset)..($Offset + 2)])
$Subtype = $Packet[($Offset + 3)]
if ($OUI -eq '00-12-BB' -and $Subtype -eq 10) {
$Hash.Add('Model', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 4)..($Offset + $Length - 1)]))
}
if ($OUI -eq '00-80-C2' -and $Subtype -eq 1) {
$Hash.Add('VLAN', [BitConverter]::ToUInt16($Packet[($Offset + 5)..($Offset + 4)], 0))
}
if ($OUI -eq '00-80-C2' -and $Subtype -eq 9) {
$ETSMask = [uint16]0x000F
$Pri0To3 = [BitConverter]::ToUInt16($Packet[($Offset + 6)..($Offset + 5)], 0)
$Pri4To7 = [BitConverter]::ToUInt16($Packet[($Offset + 8)..($Offset + 7)], 0)
$ETS = [PSCustomObject]@{
Willing = ($Packet[($Offset + 4)] -band (1 -shl 7)) -ne 0
PriorityAssignmentTable = @(
[PSCustomObject]@{
Priority = 0
TrafficClass = ($Pri0To3 -shr 12) -band $ETSMask
}
[PSCustomObject]@{
Priority = 1
TrafficClass = ($Pri0To3 -shr 8) -band $ETSMask
}
[PSCustomObject]@{
Priority = 2
TrafficClass = ($Pri0To3 -shr 4) -band $ETSMask
}
[PSCustomObject]@{
Priority = 3
TrafficClass = $Pri0To3 -band $ETSMask
}
[PSCustomObject]@{
Priority = 4
TrafficClass = ($Pri4To7 -shr 12) -band $ETSMask
}
[PSCustomObject]@{
Priority = 5
TrafficClass = ($Pri4To7 -shr 8) -band $ETSMask
}
[PSCustomObject]@{
Priority = 6
TrafficClass = ($Pri4To7 -shr 4) -band $ETSMask
}
[PSCustomObject]@{
Priority = 7
TrafficClass = $Pri4To7 -band $ETSMask
}
)
BandwidthAssignmentTable = @(
[PSCustomObject]@{
Priority = 0
Bandwidth = $Packet[($Offset + 9)]
}
[PSCustomObject]@{
Priority = 1
Bandwidth = $Packet[($Offset + 10)]
}
[PSCustomObject]@{
Priority = 2
Bandwidth = $Packet[($Offset + 11)]
}
[PSCustomObject]@{
Priority = 3
Bandwidth = $Packet[($Offset + 12)]
}
[PSCustomObject]@{
Priority = 4
Bandwidth = $Packet[($Offset + 13)]
}
[PSCustomObject]@{
Priority = 5
Bandwidth = $Packet[($Offset + 14)]
}
[PSCustomObject]@{
Priority = 6
Bandwidth = $Packet[($Offset + 15)]
}
[PSCustomObject]@{
Priority = 7
Bandwidth = $Packet[($Offset + 16)]
}
)
}
if (-not ($Hash.ContainsKey('DCBX'))) {
$Hash.Add('DCBX', [PSCustomObject]@{IEEE = [PSCustomObject]@{}})
}
$Hash.DCBX.IEEE | Add-Member -NotePropertyName ETS -NotePropertyValue $ETS
}
if ($OUI -eq '00-80-C2' -and $Subtype -eq 11) {
$PFC = [PSCustomObject]@{
Willing = ($Packet[($Offset + 4)] -band (1 -shl 7)) -ne 0
FlowControl = 0..7 | ForEach-Object {
[PSCustomObject]@{
Priority = $_
Enabled = ($Packet[($Offset + 5)] -band (1 -shl $_)) -ne 0
}
}
}