Powershell to check TCP port is open

Posted: March 14, 2011 in Networking, Scripts

Relating to my last post, I want to include not just a ping of the server, but also if I was able to open a TCP connection. In this case, to our proxy server, hence the use of port 8080.

$server = “proxyserver.domain.com”
$port = 8080

$socket = new-object Net.Sockets.TcpClient

$socket.Connect($server, $port)

if ($socket.Connected) {
$status = “Open”
$socket.Close()
}
else {
$status = “Closed / Filtered”
}

$status

Advertisements
Comments
  1. Phillip says:

    i’m a powershell newbie, how would i do this across 100 servers and check 20 ports/server?

    • dthomo says:

      Hey Phil,

      You need to wrap this code block up inside 2 For loops. The first loop for the list of servers and the second for the list of ports. The code below is an example of how to do this. You’ll need to create a text file with the list of target servers (one per line), in this example, this is placed in C:\Scripts\. You will also need to edit the array list of target ports, the variable at the top $Ports. Be sure to enclose each target port inside double quotes and separate with a comma. I quickly tested this here and works OK. The CSV output is not the best, but it will be enough to get it into Excel and work with it from there.

      $servers = Get-Content C:\Scripts\ServerList.txt
      $ports = @(“80″,”443″,”8080”)
      $ServerPortStatus = “”

      ForEach ($Server in $Servers){
      ForEach ($Port in $Ports){
      $socket = new-object Net.Sockets.TcpClient
      $socket.Connect($server, $port)

      if ($socket.Connected) {
      $status = “Open”
      $socket.Close()
      }
      else {
      $status = “Closed / Filtered”
      }
      $PortStat = $Server + “,” + $Port + “,” + $Status + “`n”
      $ServerPortStatus += $portStat

      }

      }

      $ServerPortStatus | Out-File C:\Scripts\ServerPortStatus.csv

  2. Charles Ross says:

    Thanks for this! Just FYI, the quotes in the script, as pasted from your web page, had to be replaced for it to run on my PC. Then it’s a charm.

  3. Charles Ross says:

    And here’s a version that takes host and port as argument

    Param($server , $port )

    $socket = new-object Net.Sockets.TcpClient
    $socket.Connect($server, $port)

    if ($socket.Connected) {
    $status = “Open”
    $socket.Close()
    }
    else {
    $status = ” No Answer – Closed / Filtered”
    }

    $status

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