Scanning ports on multiple hosts

Recently we had an issue that called into the use of checking to see if some ports were open and listening on our servers.  Naturally, we could have used a tool such as portqry.exe to gather this information. However, you can only use it on one system at a time which meant either incorporating it with Powershell and call the .exe when needed.  While a good idea, I wanted to build something that was free of any extra tools and just rely on Powershell itself to complete this task.

After doing some research and looking some examples online, I found that this could in fact be easily done.  Initially I was going to have it scan for TCP ports, but decided that checking UDP ports would be a good idea as well. My goal was to not only be able to scan multiple hosts, but to also scan multiple ports and report back which ones were open and which were closed.

Using the System.Net.Sockets namespace, I was able to create an object that I could then use to test both TCP and UDP ports.

$tcpobject = new-Object system.Net.Sockets.TcpClient
$udpobject = new-Object system.Net.Sockets.Udplient

I can then use the .BeginConnect() method and plug in the hostname and the port that will be tested.

$connect = $tcpobject.BeginConnect($c,$p,$null,$null)
$connect = $udpobject.BeginConnect($c,$p,$null,$null)

I then configure a timeout using the following:

$wait = $connect.AsyncWaitHandle.WaitOne($timeout,$false)

If you expand out what is in the $connect variable, you see this:

AsyncState             :
AsyncWaitHandle        : System.Threading.ManualResetEvent
CompletedSynchronously : False
IsCompleted            : True

This link explains the System.Threading.ManalResetEvent that I am using for the timeout.

The rest of the script uses the Add-Member cmdlet to add items to the created PSObject that holds all of the information for the report. I also make use of string manipulation such as Split(), Replace() and TrimStart() to make the error messages more readable in the report.

I decided to run the port scan against my local domain controller and google.com to show that some ports are open and others are not.  In the case of DC1, only TCP port 53 (DNS) was open and at google.com, TCP ports 80 (HTTP) and 443 (HTTPS) were open.


List of ports:

http://www.iana.org/assignments/port-numbers

My script is also available at the Script Repository.

Code Update 20Feb2011

Script:

function Test-Port{
<#
.SYNOPSIS
Tests port on computer.
.DESCRIPTION
Tests port on computer.
.PARAMETER computer
Name of server to test the port connection on.
.PARAMETER port
Port to test
.PARAMETER tcp
Use tcp port
.PARAMETER udp
Use udp port
.PARAMETER UDPTimeOut
Sets a timeout for UDP port query. (In milliseconds, Default is 1000)
.PARAMETER TCPTimeOut
Sets a timeout for TCP port query. (In milliseconds, Default is 1000)
.NOTES
Name: Test-Port.ps1
Author: Boe Prox
DateCreated: 18Aug2010
List of Ports: http://www.iana.org/assignments/port-numbers To Do:
Add capability to run background jobs for each host to shorten the time to scan.
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Test-Port -computer ‘server’ -port 80
Checks port 80 on server ‘server’ to see if it is listening
.EXAMPLE
‘server’ | Test-Port -port 80
Checks port 80 on server ‘server’ to see if it is listening
.EXAMPLE
Test-Port -computer @(“server1″,”server2″) -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
@(“server1″,”server2″) | Test-Port -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
(Get-Content hosts.txt) | Test-Port -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port @(1..59)
Checks a range of ports from 1-59 on all servers in the hosts.txt file

#>
[cmdletbinding(
DefaultParameterSetName = ”,
ConfirmImpact = ‘low’
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = ”,
ValueFromPipeline = $True)]
[array]$computer,
[Parameter(
Position = 1,
Mandatory = $True,
ParameterSetName = ”)]
[array]$port,
[Parameter(
Mandatory = $False,
ParameterSetName = ”)]
[int]$TCPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = ”)]
[int]$UDPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = ”)]
[switch]$TCP,
[Parameter(
Mandatory = $False,
ParameterSetName = ”)]
[switch]$UDP

)
Begin {
If (!$tcp -AND !$udp) {$tcp = $True}
#Typically you never do this, but in this case I felt it was for the benefit of the function
#as any errors will be noted in the output of the report
$ErrorActionPreference = “SilentlyContinue”
$report = @()
}
Process {
ForEach ($c in $computer) {
ForEach ($p in $port) {
If ($tcp) {
#Create temporary holder
$temp = “” | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$tcpobject = new-Object system.Net.Sockets.TcpClient
#Connect to remote machine’s port
$connect = $tcpobject.BeginConnect($c,$p,$null,$null)
#Configure a timeout before quitting
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
#If timeout
If(!$wait) {
#Close connection
$tcpobject.Close()
Write-Verbose “Connection Timeout”
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = “TCP”
$temp.Open = “False”
$temp.Notes = “Connection to Port Timed Out”
}
Else {
$error.Clear()
$tcpobject.EndConnect($connect) | out-Null
#If error
If($error[0]){
#Begin making error more readable in report
[string]$string = ($error[0].exception).message
$message = (($string.split(“:”)[1]).replace(‘”‘,””)).TrimStart()
$failed = $true
}
#Close connection
$tcpobject.Close()
#If unable to query port to due failure
If($failed){
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = “TCP”
$temp.Open = “False”
$temp.Notes = “$message”
}
#Successfully queried port
Else{
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = “TCP”
$temp.Open = “True”
$temp.Notes = “”
}
}
#Reset failed value
$failed = $Null
#Merge temp array with report
$report += $temp
}
If ($udp) {
#Create temporary holder
$temp = “” | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$udpobject = new-Object system.Net.Sockets.Udpclient($p)
#Set a timeout on receiving message
$udpobject.client.ReceiveTimeout = $UDPTimeout
#Connect to remote machine’s port
Write-Verbose “Making UDP connection to remote server”
$udpobject.Connect(“$c”,$p)
#Sends a message to the host to which you have connected.
Write-Verbose “Sending message to remote host”
$a = new-object system.text.asciiencoding
$byte = $a.GetBytes(“$(Get-Date)”)
[void]$udpobject.Send($byte,$byte.length)
#IPEndPoint object will allow us to read datagrams sent from any source.
Write-Verbose “Creating remote endpoint”
$remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)

Try {
#Blocks until a message returns on this socket from a remote host.
Write-Verbose “Waiting for message return”
$receivebytes = $udpobject.Receive([ref]$remoteendpoint)
[string]$returndata = $a.GetString($receivebytes)
}

Catch {
If ($Error[0].ToString() -match “\bRespond after a period of time\b”) {
#Close connection
$udpobject.Close()
#Make sure that the host is online and not a false positive that it is open
If (Test-Connection -comp $c -count 1 -quiet) {
Write-Verbose “Connection Open”
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = “UDP”
$temp.Open = “True”
$temp.Notes = “”
}
Else {
<#
It is possible that the host is not online or that the host is online,
but ICMP is blocked by a firewall and this port is actually open.
#>
Write-Verbose “Host maybe unavailable”
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = “UDP”
$temp.Open = “False”
$temp.Notes = “Unable to verify if port is open or if host is unavailable.”
}
}
ElseIf ($Error[0].ToString() -match “forcibly closed by the remote host” ) {
#Close connection
$udpobject.Close()
Write-Verbose “Connection Timeout”
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = “UDP”
$temp.Open = “False”
$temp.Notes = “Connection to Port Timed Out”
}
Else {
$udpobject.close()
}
}
#Merge temp array with report
$report += $temp
}
}
}
}
End {
#Generate Report
$report
}
}

About these ads

About Boe Prox

Microsoft PowerShell MVP working as a Senior Systems Administrator
This entry was posted in powershell, scripts and tagged , , , , . Bookmark the permalink.

20 Responses to Scanning ports on multiple hosts

  1. Pingback: Testing TCP Ports with a Possible Header Response | Learn Powershell | Achieve More

  2. Pingback: Multithreaded Powershell Port Scanner | Jeff's Blog

  3. Adam says:

    I’m a newbie to this, and I can’t get this to work. I’m trying to test our firewall by running a port-scan from a web frontend, to the sql server. When I try to run this, nothing happens. What do I have to do?
    Thanks

    • Boe Prox says:

      How are you running the code? Can you paste the snippet here?

      • Adam says:

        PS C:\checksqlserver> test-port
        The term ‘test-port’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the s
        pelling of the name, or if a path was included, verify that the path is correct and try again.
        At line:1 char:10
        + test-port <<< ./test-port.ps1
        PS C:\checksqlserver>

        Thanks

        • Boe Prox says:

          You will need to dot source the script prior to running the Test-Port function (if downloaded from the Script Repository):
          . .\test-port.ps1
          Test-Port -Computer testserver -port 3389 -TCP

          Hope this helps…

      • Adam says:

        Awesome Thanks

  4. stuartc says:

    Thanks for this!

    test-port has helped me greatly.I hopeyou dont mind but I’ve included the function in a script that I’ve posted on my own blog.

    @the comment above: I was of the same opinion being a long time NMAP user and used NMAP for just this but in the end the test-port function was alot better fit for what I was doing.

  5. Pingback: Powershell – Check ICA response, Check for exiestence of file and uptime of multiple remote servers » stuart@stuartc.net#

  6. Vinod says:

    This is a great Post!
    I have couple of queries
    1. Tried to export the result to .csv/xls but i couldnot able to make it any idea how to export the result?
    2. Result i wanted something like IP, port 80, Port 443, etc Results(Open or False), is this possible

    Thanks

  7. Jody Howard says:

    this looks really great. I’m new to powershell and it’s a little over my head.

    I need to find a way to determine from a client computer if ports 80 and 443 are open on a destination server

    I’m prompting the for an entry for the IP or name of the server

    #Record IP or hostname for server
    $HostnamePO=Read-Host “Enter name or IP of Server”

    and then I’m hopeless lost. Any recommendations?

    • Boe Prox says:

      Hi Jody, thanks for the comment!
      By design, the Test-Port function requires a computer and port name. If one is not given, there will be a prompt for both of these.
      For instance this example shows me adding my server (DC1) and ports 80 and 443 after each prompt.

      PS C:\Users\boe\Downloads\PowerShell_Scripts> Test-Port

      cmdlet Test-Port at command pipeline position 1
      Supply values for the following parameters:
      computer[0]: dc1
      computer[1]:
      port[0]: 80
      port[1]: 443
      port[2]:

      Server : dc1
      Port : 80
      TypePort : TCP
      Open : True
      Notes :

      Server : dc1
      Port : 443
      TypePort : TCP
      Open : True
      Notes :

      Using this should avoid you having to prompt for a hostname or ip address. If you do still want to use a prompt for this information then this would work:

      #Record IP or hostname for server
      $HostnamePO=Read-Host “Enter name or IP of Server”
      Test-Port -computer $hostnamePO -port 443,80

      Hope this helps.

  8. Cyreli says:

    I’ve been using your function for a week now, and I’m really happy with it.

    Unfortunately, I believe there is a issue with -UDP. Indeed, I’m trying to test Port 137 and Port 138 UDP. The server I’m trying to test is disconnected from the network, but the test returns True as if the ports were open.

    Thank you

  9. Pingback: Episode 128 – Kirk Munro from Quest on the 2010 PowerPack Challenge « PowerScripting Podcast

  10. Pingback: Episode 127 – Kirk Munro from Quest on the 2010 PowerPack Challenge « PowerScripting Podcast

  11. Geoff says:

    Couldn’t you just use the Windows port of NMAP ?

    • David says:

      1) It’s useless comment.
      2) In this solution you have everything in objects which is big advantage over text output from nmap.

      @boeprox: Check how you can create objects in PowerShell v2. It’s much nicer, easier and cleaner than with Add-Member. Nice script :)

      Thanks,
      David

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s