Powershell Port Scan
Table of Contents
While training Red Teaming or Penetration Test hacking on plataforms like Hack the Box or previous offensive security training like OSCP or OSEP
One thing I noticed is during lateral movement through pivoting between the machines if I had to perform port scan enumeration on hosts located on different subnet/network utilizing proxychain+nmap or chisel+nmap, that was very painful and a nightmare
Nmap + Proxychains or Nmap + chisel did not work very well for me and for that reason i came up with something different and that was to leverage what native powershell has to offer, but for the offensive security side of it
If you have to scan large amount of ports even twerking the settings in nmap and proxychains will not give much gains compared to powershell. Below is a small snipped of powershell code that I developed and used multiple times during my training days that helped me and saved me a lot of time
My personal opnion on powershell is an awesome tool and one should master and be used as Read Teamer or Penetration Tester
Powershell Port Scan Code #
I used Runspace feature in powershell that allows to run multiple commands by creating new threads on existing process. The CreateRunSpacePool values 1,100 means mininum and maximum number of threads allowed to run at the same time. The AddScript is where you add the desired code to run
$RunspacePool = [runspacefactory]::CreateRunspacePool(1,100)
$RunspacePool.Open()
$PowerShell = [powershell]::Create()
$PowerShell.RunspacePool = $RunspacePool
$PowerShell.AddScript({1..65535 | ForEach-Object { if((New-Object System.Net.Sockets.TcpClient).ConnectAsync("YOUR_IP_HERE",$_).wait(100)){write-host "Port $_ is opened"}}})
$Jobs = $PowerShell.BeginInvoke()
If you want to go beyond you can improve the code snippet to run on multiple ips or creating a script that accept IP as an argument