Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Reoccurring Processes

I am testing a few domains and their ability to alert me when an abnormal event happens. I am using nmap to scan domains for open ports. The script below opens a new cmd window and runs nmap. I search for the process ID and checks to see if the process(cmd) is still running. Once the scan is over, it will run the nmap scan again.

function nmaptest {
    $prog1="cmd"
    $params1=@("/C";"nmap.exe -Pn -sX 192.168.1.0/24")
    Start-Process -Verb runas $prog1 $params1 #starts
}

while(1 -eq 1){
    nmaptest
    $processes = get-process $prog1 | out-string
    $sp = $processes.Split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
    $procid = $sp[22]
    echo $procid

    while(get-process -id $procid){ }
}

This works fine. What I need help with is doing this process 8 times in parallel. (if that is possible)

like image 210
Harry Singh Avatar asked Sep 27 '22 20:09

Harry Singh


1 Answers

Well unless there's any specific reason you're launching CMD (such as needing to see the output) I'd recommend using jobs instead. They're easy to manage and test if they're still running.

$jobs = @()
$sx = '192.168.1.0/24', 'range2', 'etc'
For ($i = 0; $i -lt $sx.Length; $i++) { $jobs += Start-Job { nmap.exe -Pn -sX $sx[i] } }

while ($true) {
    For ($i = 0; $i -lt $sx.Length; $i++) { 
        if ($jobs[i].State -eq "Completed" {
            Write-Output ("Completed job for " + $sx[i])
            Receive-Job $jobs[i]
            $jobs[i] = Start-Job { nmap.exe -Pn -sX $sx[i] }
        } 
    }
    Start-Sleep -s 5
}
like image 63
Deadly-Bagel Avatar answered Sep 30 '22 07:09

Deadly-Bagel