The Admin Guy’s Blog

30/04/2009

Portscan with Powershell

Filed under: Powershell Scripts — The Admin Guy @ 16:25
Tags: ,

[Update 16-05-2009 – Format update]

So I found myself in need of a tool which could check whether or not one or more ports are open on a large amount of servers.

I ended up with this in powershell:

param([string]$list1,[string]$list2)
if ($list1 -eq ""){
    Write-Host "Please supply Host-list!!" -ForegroundColor Red
    break
    }
If ($list2 -eq ""){
    Write-Host "Please supply Port-List!!" -ForegroundColor Red
    break
    }
[Array]$hostlist = Get-Content $list1
[Array]$ports = Get-Content $list2
$ErrorActionPreference = "SilentlyContinue"
$ping = new-object System.Net.NetworkInformation.Ping
foreach ($ip in $hostlist) {
    $rslt = $ping.send($ip)
    if (! $?){
        Write-Host "Host: $ip - not found" -ForegroundColor Red
    }
    else {
        if ($rslt.status.tostring() –eq “Success”) {
            write-host "Host: $ip - Ports: " -foregroundColor Green -NoNewline
            foreach ($port in $ports){
                $socket = new-object System.Net.Sockets.TcpClient($ip, $port)
                if ($socket –eq $null) {
                    write-host "$port," -ForegroundColor Red -NoNewline
                }
                else {
                    write-host "$port,"-foregroundcolor Green -NoNewline
                    $socket = $null
                }
            }
        }
        else {
            write-host "Host: $ip - down" -ForegroundColor Red
        }
    }
Write-Host ""
}
$ping = $null

The script is executed in the following manner:

[ ] PS> .\script.ps1 hostlist.txt portlist.txt

In this version, the output of the script is not suited to be piped to a file, as port status is indicated with color.

3 Comments »

  1. [...] we discussed was a port scanning script from TheAdminGuy blog. Here’s the original script: http://theadminguy.wordpress.com/2009/04/30/portscan-with-powershell/. As written, there’s nothing technically wrong with it. The script gets the job done and tells [...]

    Pingback by A PowerShell Port Scan | SAPIEN Technologies — 12/05/2009 @ 18:01 | Reply

  2. I like what you’ve done here. I hope you don’t mind but I took this as a teaching opportunity for people just learning PowerShell and expanded on your solid start.

    http://blog.sapien.com/index.php/2009/05/12/a-powershell-port-scan/

    Comment by Jeffery Hicks — 12/05/2009 @ 18:04 | Reply

  3. [...] Guy @ 13:22 Tags: Active Directory, Powershell, scripts As a variation of my previously posted Portscan with powershell i wrote the following [...]

    Pingback by Powershell port ping function « The Admin Guy’s Blog — 17/05/2009 @ 13:27 | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.