-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-NetworkProcess.ps1
More file actions
730 lines (600 loc) · 24.2 KB
/
Copy pathGet-NetworkProcess.ps1
File metadata and controls
730 lines (600 loc) · 24.2 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
function Get-NetworkProcess
{
<#
.SYNOPSIS
Shows local network ports and the processes using them.
.DESCRIPTION
Retrieves active TCP and UDP sockets from the local computer and returns
structured objects that map ports to owning processes. Use -Port to find
which process is using a specific port, or use -ProcessId/-ProcessName to
show which ports a process is using.
On Windows, this function parses netstat -ano output and resolves process
names with Get-Process. On macOS and Linux, it uses lsof when available,
falling back to ss on Linux. Some operating systems hide sockets owned by
other users unless PowerShell is running with elevated privileges.
Compatible with PowerShell Desktop 5.1+ on Windows and PowerShell Core on
Windows, macOS, and Linux.
.PARAMETER Port
Local port numbers to inspect. Use -IncludeRemotePort to match remote ports as well.
.PARAMETER ProcessId
Process IDs to inspect.
.PARAMETER ProcessName
Process names to inspect. Wildcards are supported.
.PARAMETER Protocol
Protocol to include. Valid values are All, TCP, and UDP.
The default is All.
.PARAMETER IncludeRemotePort
Match -Port values against both local and remote ports.
.PARAMETER Listening
Show only listening TCP sockets and bound UDP sockets.
.PARAMETER Established
Show only established TCP connections.
.EXAMPLE
PS > Get-NetworkProcess -Port 5432
Shows the process using local port 5432.
.EXAMPLE
PS > Get-NetworkProcess -ProcessName 'postgres*'
Shows ports used by processes with names matching postgres*.
.EXAMPLE
PS > Get-NetworkProcess -ProcessId $PID
Shows network ports used by the current PowerShell process.
.EXAMPLE
PS > Get-NetworkProcess -Port 443 -IncludeRemotePort -Established
Shows established connections where either the local or remote port is 443.
.EXAMPLE
PS > 3000, 5000 | Get-NetworkProcess -Listening
Shows listening sockets for ports 3000 and 5000 using pipeline input.
.EXAMPLE
PS > Get-NetworkProcess -Protocol UDP
Shows UDP sockets and their owning processes.
.EXAMPLE
PS > Get-NetworkProcess -Listening | Sort-Object LocalPort
Shows listening TCP sockets and bound UDP sockets sorted by local port.
.EXAMPLE
PS > Get-NetworkProcess -ProcessName 'pwsh' -Protocol TCP
Shows TCP sockets owned by PowerShell processes.
.EXAMPLE
PS > Get-NetworkProcess -Port 53 -Protocol UDP
Shows UDP processes using local port 53.
.EXAMPLE
PS > Get-NetworkProcess -ProcessId 1234 -Established
Shows established TCP connections owned by process ID 1234.
.EXAMPLE
PS > Get-NetworkProcess | Sort-Object LocalPort | Format-Table -AutoSize
Protocol LocalAddress LocalPort RemoteAddress RemotePort State ProcessName ProcessId Source
-------- ------------ --------- ------------- ---------- ----- ----------- --------- ---
UDP * Unconnected identityservicesd 660 ls...
UDP * Unconnected sharingd 668 ls...
TCP * 5000 Listen ControlCenter 613 ls...
TCP * 7000 Listen ControlCenter 613 ls...
TCP 127.0.0.1 17600 Listen SomeApp 856 ls...
TCP 127.0.0.1 17603 Listen SomeApp 856 ls...
TCP 127.0.0.1 49275 Listen SomeApp 9180 ls...
TCP 127.0.0.1 49275 127.0.0.1 49695 Established SomeApp 9180 ls...
TCP 127.0.0.1 49275 127.0.0.1 49685 Established SomeApp 9180 ls...
Shows all network ports and their owning processes, sorted by local port.
.OUTPUTS
PSCustomObject
Returns objects with Protocol, LocalAddress, LocalPort, RemoteAddress,
RemotePort, State, ProcessName, ProcessId, and Source properties.
.NOTES
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/NetworkAndDns/Get-NetworkProcess.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/NetworkAndDns/Get-NetworkProcess.ps1
#>
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
[Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[Alias('LocalPort')]
[ValidateRange(1, 65535)]
[Int[]]
$Port,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('PID')]
[ValidateRange(0, 2147483647)]
[Int[]]
$ProcessId,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[SupportsWildcards()]
[ValidateNotNullOrEmpty()]
[String[]]
$ProcessName,
[Parameter()]
[ValidateSet('All', 'TCP', 'UDP')]
[String]
$Protocol = 'All',
[Parameter()]
[Switch]
$IncludeRemotePort,
[Parameter()]
[Switch]
$Listening,
[Parameter()]
[Switch]$Established,
[Parameter(DontShow = $true)]
[String[]]
$RawConnectionOutput,
[Parameter(DontShow = $true)]
[ValidateSet('Auto', 'Lsof', 'Netstat', 'Ss')]
[String]
$InputFormat = 'Auto'
)
begin
{
if ($Listening -and $Established)
{
throw '-Listening and -Established cannot be used together.'
}
$requestedPorts = New-Object System.Collections.ArrayList
$processNameById = @{}
if ($PSVersionTable.PSVersion.Major -lt 6)
{
$isWindowsPlatform = $true
$isMacOSPlatform = $false
$isLinuxPlatform = $false
}
else
{
$isWindowsPlatform = $IsWindows
$isMacOSPlatform = $IsMacOS
$isLinuxPlatform = $IsLinux
}
function ConvertFrom-NetworkEndpoint
{
param(
[AllowNull()]
[String]$Endpoint
)
$address = ''
$port = $null
if ([String]::IsNullOrWhiteSpace($Endpoint))
{
return [PSCustomObject]@{
Address = $address
Port = $port
}
}
$endpointText = $Endpoint.Trim()
$portText = ''
if ($endpointText -match '^\[(?<Address>.+)\]:(?<Port>[^:]+)$')
{
$address = $Matches.Address
$portText = $Matches.Port
}
else
{
$separatorIndex = $endpointText.LastIndexOf(':')
if ($separatorIndex -ge 0)
{
$address = $endpointText.Substring(0, $separatorIndex)
$portText = $endpointText.Substring($separatorIndex + 1)
}
else
{
$address = $endpointText
}
}
$address = $address.Trim()
if ($address.StartsWith('[') -and $address.EndsWith(']') -and $address.Length -gt 1)
{
$address = $address.Substring(1, $address.Length - 2)
}
if ([String]::IsNullOrWhiteSpace($address))
{
$address = '*'
}
if (-not [String]::IsNullOrWhiteSpace($portText) -and $portText -ne '*')
{
$parsedPort = 0
if ([Int]::TryParse($portText, [ref]$parsedPort))
{
$port = $parsedPort
}
else
{
$port = $portText
}
}
[PSCustomObject]@{
Address = $address
Port = $port
}
}
function ConvertTo-NetworkPortState
{
param(
[AllowNull()]
[String]$State,
[AllowNull()]
[String]$Protocol
)
if ([String]::IsNullOrWhiteSpace($State))
{
if ($Protocol -and $Protocol.ToUpperInvariant() -eq 'UDP')
{
return 'Unconnected'
}
return ''
}
$stateText = $State.Trim()
$normalizedState = $stateText.ToUpperInvariant().Replace('-', '_')
switch -Regex ($normalizedState)
{
'^LISTEN(ING)?$' { return 'Listen' }
'^ESTAB(LISHED)?$' { return 'Established' }
'^UNCONN(ECTED)?$' { return 'Unconnected' }
'^TIME_WAIT$' { return 'TimeWait' }
'^CLOSE_WAIT$' { return 'CloseWait' }
'^SYN_SENT$' { return 'SynSent' }
'^SYN_RECV$' { return 'SynReceived' }
'^FIN_WAIT_?1$' { return 'FinWait1' }
'^FIN_WAIT_?2$' { return 'FinWait2' }
'^LAST_ACK$' { return 'LastAck' }
'^CLOSING$' { return 'Closing' }
'^CLOSED$' { return 'Closed' }
default { return $stateText }
}
}
function Get-ProcessNameById
{
param(
[Int]$Id
)
if ($Id -le 0)
{
return ''
}
if ($processNameById.ContainsKey($Id))
{
return $processNameById[$Id]
}
try
{
$process = Get-Process -Id $Id -ErrorAction Stop | Select-Object -First 1
$resolvedName = if ($process) { $process.ProcessName } else { '' }
}
catch
{
$resolvedName = ''
}
$processNameById[$Id] = $resolvedName
return $resolvedName
}
function ConvertTo-NetworkPortProcessObject
{
param(
[AllowNull()]
[String]$Protocol,
[AllowNull()]
[String]$LocalEndpoint,
[AllowNull()]
[String]$RemoteEndpoint,
[AllowNull()]
[String]$State,
[Int]$ProcessId,
[AllowNull()]
[String]$ProcessName,
[String]$Source
)
$protocolText = if ($Protocol) { $Protocol.ToUpperInvariant() } else { '' }
$local = ConvertFrom-NetworkEndpoint -Endpoint $LocalEndpoint
$remote = ConvertFrom-NetworkEndpoint -Endpoint $RemoteEndpoint
[PSCustomObject]@{
PSTypeName = 'Network.PortProcess'
Protocol = $protocolText
LocalAddress = $local.Address
LocalPort = $local.Port
RemoteAddress = $remote.Address
RemotePort = $remote.Port
State = ConvertTo-NetworkPortState -State $State -Protocol $protocolText
ProcessName = if ($ProcessName) { $ProcessName } else { Get-ProcessNameById -Id $ProcessId }
ProcessId = $ProcessId
Source = $Source
}
}
function ConvertFrom-LsofConnectionOutput
{
param(
[String[]]$InputObject
)
$currentProcessId = 0
$currentProcessName = ''
$currentProtocol = ''
$currentEndpoint = ''
$currentState = ''
function Add-LsofConnection
{
if ([String]::IsNullOrWhiteSpace($currentProtocol) -or [String]::IsNullOrWhiteSpace($currentEndpoint))
{
return
}
$endpointParts = $currentEndpoint -split '->', 2
$localEndpoint = $endpointParts[0]
$remoteEndpoint = if ($endpointParts.Count -gt 1) { $endpointParts[1] } else { '' }
ConvertTo-NetworkPortProcessObject -Protocol $currentProtocol -LocalEndpoint $localEndpoint -RemoteEndpoint $remoteEndpoint -State $currentState -ProcessId $currentProcessId -ProcessName $currentProcessName -Source 'lsof'
}
foreach ($line in $InputObject)
{
if ([String]::IsNullOrWhiteSpace($line) -or $line.Length -lt 2)
{
continue
}
$fieldName = $line.Substring(0, 1)
$fieldValue = $line.Substring(1)
switch -CaseSensitive ($fieldName)
{
'p'
{
Add-LsofConnection
$parsedProcessId = 0
if ([Int]::TryParse($fieldValue, [ref]$parsedProcessId))
{
$currentProcessId = $parsedProcessId
}
else
{
$currentProcessId = 0
}
$currentProcessName = ''
$currentProtocol = ''
$currentEndpoint = ''
$currentState = ''
}
'c'
{
$currentProcessName = $fieldValue
}
'P'
{
Add-LsofConnection
$currentProtocol = $fieldValue.ToUpperInvariant()
$currentEndpoint = ''
$currentState = ''
}
'n'
{
$currentEndpoint = $fieldValue
}
'T'
{
if ($fieldValue -match '^ST=(.+)$')
{
$currentState = $Matches[1]
}
}
}
}
Add-LsofConnection
}
function ConvertFrom-NetstatConnectionOutput
{
param(
[String[]]$InputObject
)
foreach ($line in $InputObject)
{
if ([String]::IsNullOrWhiteSpace($line))
{
continue
}
$trimmedLine = $line.Trim()
if ($trimmedLine -notmatch '^(TCP|UDP)\s+')
{
continue
}
$parts = $trimmedLine -split '\s+'
$protocolText = $parts[0].ToUpperInvariant()
if ($protocolText -eq 'TCP' -and $parts.Count -ge 5)
{
$parsedProcessId = 0
[void][Int]::TryParse($parts[4], [ref]$parsedProcessId)
ConvertTo-NetworkPortProcessObject -Protocol $protocolText -LocalEndpoint $parts[1] -RemoteEndpoint $parts[2] -State $parts[3] -ProcessId $parsedProcessId -ProcessName '' -Source 'netstat'
}
elseif ($protocolText -eq 'UDP' -and $parts.Count -ge 4)
{
$parsedProcessId = 0
[void][Int]::TryParse($parts[$parts.Count - 1], [ref]$parsedProcessId)
ConvertTo-NetworkPortProcessObject -Protocol $protocolText -LocalEndpoint $parts[1] -RemoteEndpoint $parts[2] -State '' -ProcessId $parsedProcessId -ProcessName '' -Source 'netstat'
}
}
}
function ConvertFrom-SsConnectionOutput
{
param(
[String[]]$InputObject
)
foreach ($line in $InputObject)
{
if ([String]::IsNullOrWhiteSpace($line))
{
continue
}
$trimmedLine = $line.Trim()
if ($trimmedLine -notmatch '^(tcp|udp)\s+')
{
continue
}
$parts = $trimmedLine -split '\s+'
if ($parts.Count -lt 6)
{
continue
}
$protocolText = if ($parts[0] -like 'tcp*') { 'TCP' } else { 'UDP' }
$stateText = $parts[1]
$localEndpoint = $parts[4]
$remoteEndpoint = $parts[5]
$processText = if ($parts.Count -gt 6) { $parts[6..($parts.Count - 1)] -join ' ' } else { '' }
$parsedProcessId = 0
$resolvedProcessName = ''
if ($processText -match '"(?<Name>(?:[^"\\]|\\.)*)",pid=(?<ProcessId>\d+)')
{
$resolvedProcessName = $Matches.Name -replace '\\"', '"'
[void][Int]::TryParse($Matches.ProcessId, [ref]$parsedProcessId)
}
elseif ($processText -match 'pid=(?<ProcessId>\d+)')
{
[void][Int]::TryParse($Matches.ProcessId, [ref]$parsedProcessId)
}
ConvertTo-NetworkPortProcessObject -Protocol $protocolText -LocalEndpoint $localEndpoint -RemoteEndpoint $remoteEndpoint -State $stateText -ProcessId $parsedProcessId -ProcessName $resolvedProcessName -Source 'ss'
}
}
function ConvertFrom-RawConnectionOutput
{
param(
[String[]]$InputObject,
[String]$Format
)
$resolvedFormat = $Format
if ($resolvedFormat -eq 'Auto')
{
if ($InputObject | Where-Object { $_ -match '^p\d+$' } | Select-Object -First 1)
{
$resolvedFormat = 'Lsof'
}
elseif ($InputObject | Where-Object { $_ -match '^\s*(TCP|UDP)\s+' } | Select-Object -First 1)
{
$resolvedFormat = 'Netstat'
}
else
{
$resolvedFormat = 'Ss'
}
}
switch ($resolvedFormat)
{
'Lsof' { ConvertFrom-LsofConnectionOutput -InputObject $InputObject }
'Netstat' { ConvertFrom-NetstatConnectionOutput -InputObject $InputObject }
'Ss' { ConvertFrom-SsConnectionOutput -InputObject $InputObject }
}
}
function Get-NativeNetworkPortProcess
{
if ($isWindowsPlatform)
{
$netstatCommand = Get-Command -Name 'netstat' -CommandType Application -ErrorAction SilentlyContinue
if (-not $netstatCommand)
{
Write-Error "The 'netstat' command was not found. Cannot inspect local network ports on this Windows system."
return
}
Write-Verbose 'Inspecting network ports with netstat -ano'
$netstatOutput = & netstat -ano 2>&1
ConvertFrom-NetstatConnectionOutput -InputObject $netstatOutput
return
}
$lsofCommand = Get-Command -Name 'lsof' -CommandType Application -ErrorAction SilentlyContinue
if ($lsofCommand)
{
Write-Verbose 'Inspecting network ports with lsof'
$lsofOutput = & lsof -nP -iTCP -iUDP -F pcPnT 2>&1
ConvertFrom-LsofConnectionOutput -InputObject $lsofOutput
return
}
if ($isLinuxPlatform)
{
$ssCommand = Get-Command -Name 'ss' -CommandType Application -ErrorAction SilentlyContinue
if ($ssCommand)
{
Write-Verbose 'Inspecting network ports with ss -H -tunap'
$ssOutput = & ss -H -tunap 2>&1
ConvertFrom-SsConnectionOutput -InputObject $ssOutput
return
}
}
$platformName = if ($isMacOSPlatform) { 'macOS' } elseif ($isLinuxPlatform) { 'Linux' } else { 'this platform' }
Write-Error "No supported network/process inventory command was found on $platformName. Install 'lsof' or, on Linux, 'ss'."
}
function Test-NetworkPortProcessMatch
{
param(
[Parameter(Mandatory)]
[PSCustomObject]$Connection,
[Int[]]$PortsToMatch,
[Int[]]$ProcessIdsToMatch,
[String[]]$ProcessNamesToMatch
)
if ($Protocol -ne 'All' -and $Connection.Protocol -ne $Protocol)
{
return $false
}
if ($PortsToMatch -and $PortsToMatch.Count -gt 0)
{
$portMatches = $false
if ($null -ne $Connection.LocalPort -and $Connection.LocalPort -is [Int])
{
$portMatches = $PortsToMatch -contains $Connection.LocalPort
}
if (-not $portMatches -and $IncludeRemotePort -and $null -ne $Connection.RemotePort -and $Connection.RemotePort -is [Int])
{
$portMatches = $PortsToMatch -contains $Connection.RemotePort
}
if (-not $portMatches)
{
return $false
}
}
if ($ProcessIdsToMatch -and $ProcessIdsToMatch.Count -gt 0 -and $ProcessIdsToMatch -notcontains $Connection.ProcessId)
{
return $false
}
if ($ProcessNamesToMatch -and $ProcessNamesToMatch.Count -gt 0)
{
$connectionProcessName = [String]$Connection.ProcessName
$processNameMatches = $false
foreach ($processNamePattern in $ProcessNamesToMatch)
{
if ($connectionProcessName -like $processNamePattern)
{
$processNameMatches = $true
break
}
}
if (-not $processNameMatches)
{
return $false
}
}
if ($Listening -and $Connection.State -ne 'Listen' -and -not ($Connection.Protocol -eq 'UDP' -and $Connection.State -eq 'Unconnected'))
{
return $false
}
if ($Established -and $Connection.State -ne 'Established')
{
return $false
}
return $true
}
}
process
{
if ($Port)
{
foreach ($portNumber in $Port)
{
[void]$requestedPorts.Add($portNumber)
}
}
}
end
{
$portsToMatch = @($requestedPorts | Sort-Object -Unique)
$processIdsToMatch = if ($PSBoundParameters.ContainsKey('ProcessId')) { @($ProcessId | Sort-Object -Unique) } else { @() }
$processNamesToMatch = if ($PSBoundParameters.ContainsKey('ProcessName')) { @($ProcessName) } else { @() }
$connections = if ($PSBoundParameters.ContainsKey('RawConnectionOutput'))
{
ConvertFrom-RawConnectionOutput -InputObject $RawConnectionOutput -Format $InputFormat
}
else
{
Get-NativeNetworkPortProcess
}
$connections |
Where-Object {
Test-NetworkPortProcessMatch -Connection $_ -PortsToMatch $portsToMatch -ProcessIdsToMatch $processIdsToMatch -ProcessNamesToMatch $processNamesToMatch
} |
Sort-Object -Property Protocol, LocalAddress, LocalPort, RemoteAddress, RemotePort, State, ProcessName, ProcessId -Unique
}
}