PowerShell: Check TCP Connections of Server by Port Numbers

# Check-TCP-Connections.ps1
# This function will output progress onto the console as well as returning a Array Object to be consumed by a program

# Set Variables of server and ports to check
$server="SOMEsherver";
$ports=@(445,139);

function checkTcpConnections {
Param (
[string]$Server = "localhost",
[int[]]$Ports = @(445,139) #default SMB ports
)
$session=New-PSSession -ComputerName $server
$results=invoke-command -Session $session -ScriptBlock{
param($ports)

write-host "Collecting raw connection data..."
$connections=[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpConnections()|?{$_.State -eq "Established"}

write-host "Refining raw results for matches connections to local port(s) of $ports..."
$connectionsRefined=@()
for ($i=0;$i -lt $connections.count;$i++){
$thisConnection=$connections[$i]
$index=$i
$localIp=$([void]($thisConnection.LocalEndpoint -match "(.*):");$matches[1];)
$localPort = $thisconnection.LocalEndPoint.tostring().substring($localip.Length+1)
if ($ports -contains [int]$localPort){
$remoteIp=$([void]($thisConnection.RemoteEndpoint -match "(.*):");$matches[1];)
$remotePort=$thisconnection.RemoteEndpoint.tostring().substring($remoteIp.Length+1)
$remoteComputerName=try{[System.Net.dns]::gethostentry([string]$remoteIp).Hostname}catch{}
if ($remoteComputerName){write-host "$remoteIp`: $remoteComputerName"}
$State=$thisConnection.State;
$connectionsRefined+=[PSCustomObject]@{index=$index;localIp=$localIp;localPort=$localPort;remoteComputerName=$remoteComputerName;remoteIp=$remoteIp;remotePort=$remotePort;State=$State};
}else{
continue;
}
}
return $connectionsRefined
} -args $ports

Remove-PSSession $session
write-host "`r`n------------------Here are the results:`r`n--------------------"
return $results;
}

checkTcpConnections -Server $server -Ports $ports

Sample Output:

<# Sample Output
index : 252
localIp : 5.5.5.5
localPort : 445
remoteComputerName : yamama.kimconnect.com
remoteIp : 256.500.400.1000
remotePort : 59920
State : Established
PSComputerName : cigarettesSuck
RunspaceId : 8d552cf5-a0bc-4473-b87c-04c54432a8f4

index : 253
localIp : 5.5.5.5
localPort : 445
remoteComputerName : contra.kimconnect.com
remoteIp : 256.500.400.4000
remotePort : 53957
State : Established
PSComputerName : cigarettesSuck
RunspaceId : 8d552cf5-a0bc-4473-b87c-04c54432a8f4

index : 254
localIp : 5.5.5.5
localPort : 445
remoteComputerName : 3yamama.kimconnect.com
remoteIp : 256.500.400.3000
remotePort : 58733
State : Established
PSComputerName : cigarettesSuck
RunspaceId : 8d552cf5-a0bc-4473-b87c-04c54432a8f4

index : 255
localIp : 5.5.5.5
localPort : 445
remoteComputerName : yamama5.kimconnect.com
remoteIp : 256.500.400.2000
remotePort : 61791
State : Established
PSComputerName : cigarettesSuck
RunspaceId : 8d552cf5-a0bc-4473-b87c-04c54432a8f4
#>

Leave a Reply

Your email address will not be published. Required fields are marked *