top of page

PowerShell - TCP port scanner

  • Writer: Jon Boyette
    Jon Boyette
  • Mar 1, 2022
  • 1 min read

Save as port-scan-tcp.ps1, use the examples in the script to run across many computers from text. and ports simultaneously.

#Function port-scan-tcp {

param($hosts,$ports)

if (!$ports) {

Write-Host "usage: .\port-scan-tcp.ps1 (gc c:\temp\servers.txt) (135,137,445)"

Write-Host " e.g.: port-scan-tcp 192.168.1.2 445`n"

return

}

$out = "c:\temp\scanresults.txt"

foreach($p in [array]$ports) {

foreach($h in [array]$hosts) {

$x = (gc $out -EA SilentlyContinue | select-string "^$h,tcp,$p,")

if ($x) {

gc $out | select-string "^$h,tcp,$p,"

continue

}

$msg = "$h,tcp,$p,"

$t = new-Object system.Net.Sockets.TcpClient

$c = $t.ConnectAsync($h,$p)

for($i=0; $i -lt 10; $i++) {

if ($c.isCompleted) { break; }

sleep -milliseconds 100

}

$t.Close();

$r = "Filtered"

if ($c.isFaulted -and $c.Exception -match "actively refused") {

$r = "Closed"

} elseif ($c.Status -eq "RanToCompletion") {

$r = "Open"

}

$msg += $r

Write-Host "$msg"

echo $msg >>$out

}

}


# .NET 4.5


# Examples:

#

# port-scan-tcp 10.10.0.1 137

# port-scan-tcp 10.10.0.1 (135,137,445)

# port-scan-tcp (gc .\ips.txt) 137

# port-scan-tcp (gc .\ips.txt) (135,137,445)

# 0..255 | foreach { port-scan-tcp 10.10.0.$_ 137 }

# 0..255 | foreach { port-scan-tcp 10.10.0.$_ (135,137,445) }


 
 
 

Recent Posts

See All
PowerShell - List All Domain SPNs

Save as same List_ALL_SPNs.ps1 or similar, this LDap calls the Domain for all Service Principal names and accounts related #Build LDAP...

 
 
 
PowerShell - Start-Monitoring

This is a great script used to Monitor and Email if a server is up or down, once ran, and smtp and from address is set, then run:...

 
 
 

Comments


Post: Blog2 Post
  • Facebook
  • Twitter
  • LinkedIn

©2022 by Boyette Technical Services. Proudly created with Wix.com

bottom of page