Wednesday, January 15, 2014

What I learnt at the Winter Scripting Games - Part 1 - Subnet Scanner

We're done with the practice event for the winter scripting games and one of the first requirements was a subnet scanner! I've always wanted one of those! So we wrote one and it's here for you to use;
$MaxThreads = 20
$network = "192.168.92."
#$subnet = "24" #TODO... set $rangestart and $rangeend to the appropriate values based of subnet... Anyone know how to achieve that algorithmically? We'll just leave it as a manual setting for now
$rangestart = 1
$rangeend = 254
$counter = $rangestart

$scriptblock = {param($ip)
    $temp ="" | Select-Object IP, Status
    $temp.status = "Fail"
    $test = $null
    $temp.ip = $ip 
    $test = test-connection $ip -count 1
    if ($test -ne $null)
    {
        $temp.Status = "Success"
    }
    write-output $temp -NoEnumerate
}

while ($counter -le $rangeend)

    Write-Progress  -Activity "Pinging $ip" -Status "Waiting for threads to close" -CurrentOperation ("" + $counter + " threads created - " + ((Get-Job -state running).count) + " threads open"-PercentComplete $prog
    $prog = ($counter / $rangeend* 100  
    $ip = $network + $counter.ToString()
    While ($(Get-Job -state running).count -ge $MaxThreads)
    {
         Write-Progress  -Activity "Pinging $ip" -Status "Waiting for threads to close" -CurrentOperation ("" + $counter + " threads created - " + ((Get-Job -state running).count) + " threads open"-PercentComplete $prog
    }
    Start-job -ArgumentList $ip, $outputpath -scriptblock $scriptblock -Name ("subnetscans"+$ip| out-null
    $counter++
    start-sleep -Milliseconds 200
}
$report = Get-Job -Filter "name -like 'subnetscans*'" | Receive-Job -wait
$report | select IP, Status
This is a neat example of using start-job to create a multi-threaded script.

No comments:

Post a Comment