Monitoring with PowerShell: External port scanning

So I like knowing exactly what ports are open on my clients network, and have the ability to alert on specific ports that are opened. The problem with most port-scan utilities, and the PowerShell Test-netconnection cmdlet is that they always scan the internal network. In the case that you do enter the external IP whitelisting might allow you to connect anyway and give you some false positives.

To resolve this I’ve created a php page to be used in conjunction with a PowerShell script. The reason I’ve created the page is that I do not like relying on external web based API IP scans. Also I don’t want to be stuck in any subscription model for something as simple as a port scan. With this method you are also completely in control of the source.

So let’s get started! First off you’ll have to upload the following file as “scan.php” to any PHP host. You can browse to the page and it should show you some JSON information regarding the scan it performs on your IP. Scan.php is based on this Github script.

<?php
$host = $_SERVER['REMOTE_ADDR'];
$ports = array(
    21,
    25,
    80,
    3389,
    1234,
    3333,
    3389,
    33890,
    3380
);
foreach ($ports as $port)
{
    $connection = @fsockopen($host, $port, $errno, $errstr, 2);
    if (is_resource($connection))
    {
        echo '{' . '"Port":' . $port . ',' . '"status" : "open"' . "},";
        fclose($connection);
    }
    else
    {
        echo '{' . '"Port":' . $port . ', "status" : "closed"},';
    }
} ?> { "result": "done" } ]

I’ve converted the original github page to return only JSON. The good thing is that we can use the Invoke-restmethod cmdlet straight away, without having to convert anything, The PowerShell script can be edited to alert only on specific ports that are opened, or on all open ports.

$Results = invoke-restmethod -uri "http://YOURWEBHOST.COM/ip/scan.php"
$OpenPorts = $Results | Where-Object { $_.status -eq "open"}
$ClosedPorts = $Results | Where-Object { $_.status -eq "closed"}

if(!$OpenPorts) {
$PortScanResult = "Healthy"
} else {
$PortScanResult = $OpenPorts
}

And that’s it! as always Happy PowerShelling!

Kelvin Tegelaar
Follow me

2 thoughts on “Monitoring with PowerShell: External port scanning

  1. David

    Great post! I only see a few lines where it appears the entire scan.php code should be. Can you fix the post or possibly just send me the code? Thanks!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.