EvilZone

Programming and Scripting => Beginner's Corner => : jpHernandez January 09, 2015, 11:59:15 PM

: [Powershell] Build your very simple Port Scanner
: jpHernandez January 09, 2015, 11:59:15 PM
This code is written in PowerShell, a very simple port scanner

: (powershell)
$device = $args[0]
$port = $args[1]
$start = $args[2]
$stop = $args[3]


function pingdevice()
{
    if(Test-Connection $device -ErrorAction SilentlyContinue)
    {
        Write-Output "$device is up"
        Write-Output "-----------------"
        }
    else
    {
        Write-Output "$device is down"
        Write-Output "-----------------"
        exit
        }
}


function checkports()
{
    if($port -match "multi")
    {
        for($counter=$start; $counter -le $stop; $counter++)
        {
            $porttest = New-Object Net.Sockets.TcpClient
            try
            {
                $connect = $porttest.Connect($device,$counter)
                write-ouput "port $counter is open"
                }
            catch
            {
                Write-Output "port $counter is closed"
                }
         }
    }
    else
    {
        $porttest = New-Object Net.Sockets.TcpClient
        try
        {
            $connect = $porttest.Connect($device,$port)
            Write-Output "port $port is open"
            }
        catch
        {
            write-output "port $port is closed"
            }
    }
}


write-output ""


pingdevice
checkports


Write-Output ""
Cheers,
jph :)
: Re: [Powershell] Build your very simple Port Scanner
: kenjoe41 January 13, 2015, 03:58:36 PM
I have never done powershell but i think it is still the same rules so here we go.

It is not a good practice generally to do I/O from every single function you have. You could adopt a practice of using a script/scriptblock that calls all you functions/subroutines from it and do you I/O from it.  Your Test-Connection $device method could also use a time out value though if you think you are good with the default one, no problem.

In other languages, those could be global variables, right? And i think this is a poor way of managing commandline args since powershell comes bundled with a way to do it better.
: (powershell)
param (
    [string]$device = $(throw "-device name is required."),
    [int]$port,
    [int]$start = 100,  <# default start port #>
    [int]$stop = 299, <# default stop port #>
 )
Have a look at https://devcentral.f5.com/articles/powershell-abcs-p-is-for-parameters (https://devcentral.f5.com/articles/powershell-abcs-p-is-for-parameters)


Look at this for inspiration, improving and learning on how best this could be done in poweshell: https://github.com/attackdebris/babel-sf/blob/master/powershell/portscan-powershell.ps1 (https://github.com/attackdebris/babel-sf/blob/master/powershell/portscan-powershell.ps1)