Thursday 7 June 2012

Powershell port scanner

OK; this code is shocking, I wouldn't even bother using it, I'm only putting it here so I don't lose it ;)


echo "      ##############################################
      #############Simple port scanner##############
      ##############################################
      ################### Usage ####################
      #.\portscanner   #
      ##.\portscanner bing.com multi 0 65535 #######
      ###########.\portscanner bing.com 445 ########
      ##############################################"


### arguments

$device = $args[0]
$port = $args[1]
$start = $args[2]
$stop = $args[3]

### function ping device

function pingdevice{
    if(test-connection $device -erroraction silentlycontinue){
        write-output "$device is up"
    }else{
        write-output "$device is down"
        exit
    }
}

### function check ports

function checkports{
    if ($port -match "multi"){ ### checks port range
        for ($counter=$start; $counter -le $stop; $counter++)
        {
            write-output "testing port $counter on $device"
            $porttest = new-object Net.Sockets.TcpClient
            try{
                $connect = $porttest.connect($device,$counter)
                write-output "$counter is open"
            }catch{
                write-output "$counter is closed"
            
            }                                             
    }
    }else{ ## checks a single port
        write-output "testing port $port on $device"
        $porttest = new-object Net.Sockets.TcpClient
        try{
            $connect = $porttest.connect($device,$port)
            write-output "$port is open"
        }catch{
            write-output "$port is closed"
        }
    }
}                                                 
# run out functions
pingdevice
checkports