Have you ever needed to test if a particular firewall rule is enabled and actually functioning as expected? Of course you had! A great friend and a colleague passed this gem along to me that allows you to create a simple ‘port listener’ on any Windows machine using PowerShell.
Simply click start, type in ‘PowerShell’, and run ‘Windows PowerShell’, and copy/paste this script into the ‘Windows PowerShell’ window.
$port = 9999; $Listener = [System.Net.Sockets.TcpListener]$port; $Listener.Start(); while($true) $client = $Listener.AcceptTcpClient(); Write-Host "Connection on port $port from $($client.client.RemoteEndPoint.Address)"; $client.Close(); }
Then, attempt to log access the specified port, in this case, we choose 9999 via the web browser or telnet:
This will result in the following output in the PowerShell window:
Connection on port 9999 from A.B.C.D
Where A.B.C.D is the source IP address from which the connection attempt is made. This is a great and simple way of testing firewall rules, NAT rules, Loadbalancing or even L4 hashing (across aggregated port-channels/LACP links).
Thanks, this is really handy. I’ve added this function to my Powershell profile:
Function Test-Port ([Parameter(Mandatory=$true)][int]$port)
{
$listener = [System.Net.Sockets.TcpListener]$port
$listener.Start()
While ($true)
{
$client = $listener.AcceptTcpClient()
Write-Host (“Connection on port ” + $port + ” from ” + $client.Client.RemoteEndPoint.Address)
$client.Close()
}
}
Cool. Please do tell me more about your PowerShell profile, how it’s used, what it does, etc. This it’s almost literally the first time I’m using PowerShell…
Also let me know if there are other topics of interest that you may be interested in hearing about on my blog 🙂
Your Powershell profile is basically just a file that gets run when you open Powershell. You can see the location of your profile file by typing: $profile into a Powershell window. If you edited the .ps1 file in Notepad and pasted the above function into it, when you next opened Powershell you would be able to type: Test-Port -port 9999 directly into the prompt. It saves a lot of copy-pasting :).
I also just discovered the profile file doesn’t exist by default. You can check whether it exists with this:
Test-Path $profile
And if it returns false, you can create the file with this:
New-Item $profile -ItemType File
Nice – that’s even better – thank you!