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.

$host = $_SERVER['REMOTE_ADDR'];
$ports = array(
foreach ($ports as $port)
    $connection = @fsockopen($host, $port, $errno, $errstr, 2);
    if (is_resource($connection))
        echo '{' . '"Port":' . $port . ',' . '"status" : "open"' . "},";
        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!

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!


Leave a Reply

