Home > Enterprise >  powershell test connection for all port
powershell test connection for all port

Time:11-17

If you had to test port 389, 636, 3268, and 3269 on over 300 machines as quickly as possible using PowerShell, how would you do it? Is PowerShell the right answer for this?

need output like below:-

Hostname 389 636 443

Server 1 Pass Pass Pass Server 2 Pass Pass Pass

CodePudding user response:

In PowerShell 7.0 :

"example.com","example.net","example.org" `
| ForEach-Object { 
    $computer = $_
    $ports = 389,636,3268,3269
    Write-Output $computer
    foreach ($port in $ports) {
        Write-Output $port
        Test-Connection -ComputerName $computer -TcpPort $port
    }
}

Will output:

example.com
389
False
636
False
3268
False
3269
False
example.net
389
False
636
False
3268
False
3269
False
example.org
389
False
636
False
3268
False
3269
False

Alternatively, in Windows PowerShell 5.1:

"example.com","example.net","example.org" `
| ForEach-Object { 
    $computer = $_
    $ports = 389,636,3268,3269
    Write-Output $computer
    foreach ($port in $ports) {
        Write-Output $port
        Test-NetConnection -ComputerName $computer -Port $port
    }
}

as quickly as possible (...) Is PowerShell the right answer for this?

If by as quickly as possible you mean shortest execution time, then PowerShell is most definitely NOT the right answer. It'll do the job, but there are faster languages out there.

CodePudding user response:

This is tested in Powershell 7.2

$hostlist = 'Server1','Server2','Server3','Server4'

$portlist = 389, 636, 3268, 3269

$syncedht = [HashTable]::Synchronized(@{})

$hostlist | ForEach-Object -Parallel {

    $ht = $using:syncedht
    $ht[$_] = [ordered]@{Name=$_}
    $timeout = 500

    $using:portlist | ForEach-Object -Parallel {

        $ht = $using:ht
        $obj = New-Object System.Net.Sockets.TcpClient
        $ht[$using:_].$_ = ('Fail','Pass')[$obj.ConnectAsync($Using:_, $_).Wait($using:timeout)]

    } -ThrottleLimit 8

    [PSCustomObject]$ht[$_]

} -ThrottleLimit 32 -OutVariable results

You can increase the ThrottleLimit and can pipe it straight to Export-Csv

CodePudding user response:

I'd use PowerShell to run NMap.

nmap.exe -p 389,636,3268,3269 -iL computers.txt

(Command line taken from this site )

CodePudding user response:

$comp = "abc", "xyz" $ports = "389","636","53" foreach ($port in $ports) { Write-Output $port Test-NetConnection -computername $comp -Port $port |Out-String }
  • Related