Skip to content

Instantly share code, notes, and snippets.

@orangeblock
Last active March 27, 2021 15:31
Show Gist options
  • Save orangeblock/4a5ebc3fa5a6a3779edd611ed6a6f234 to your computer and use it in GitHub Desktop.
Save orangeblock/4a5ebc3fa5a6a3779edd611ed6a6f234 to your computer and use it in GitHub Desktop.
Powershell script to check which hosts have a port open. You can use it without any arguments to scan local addresses [192.168.1.2 - 192.168.1.30] for port 22, or use the arguments at the top to specify various properties.
param(
[string]$HostPrefix = "192.168.1.",
[int]$Port = 22,
[int]$StartIndex = 2,
[int]$EndIndex = 30,
[int]$ConnectTimeout = 150
)
function testport ($hostname, $port, $timeout) {
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect($hostname, $port, $null, $null)
Start-Sleep -milli $timeout
if ($client.Connected) { $open = $true } else { $open = $false }
$client.Close()
return $open
}
"Trying port [$Port] for [$HostPrefix$StartIndex...$HostPrefix$EndIndex]"
For ($i=$StartIndex; $i-le $EndIndex; $i++){
$_host="$HostPrefix$i"
$res = testport $_host $Port $ConnectTimeout
if($res -eq $true){
"$_host [open]"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment