0

I am writing a script where I take IP adresses from netstat, and based on those I want to run a specific command for each IP. This command connects to the IP and outputs some text in the terminal. If the command cannot connect it will timeout after around 35 seconds, which makes the script slow.

Here is what I am trying to do: Get the IP adresses from netstat and piping them onward - done For each IP address, run a command, like "mycommand $IP" but run it in paralell. After X seconds, kill all the PIDs of the commands.

Here on stackoverflow I found a script that does this.

#!/bin/bash

for cmd in "$@"; do {
echo "Process \"$cmd\" started";
$cmd & pid=$!
PID_LIST+=" $pid";
} done

echo "Parallel processes have started";
sleep 5
for id in $PID_LIST
do
    kill $id
done

echo
echo "All processes have completed";

And it works if you use it like:

./paralell.sh "mycommand 1.1.1.1" "mycommand 2.2.2.2" "mycommand 3.3.3.3"

The trouble I am having is how to get the piped input that looks like this

mycommand 1.1.1.1
mycommand 2.2.2.2
mycommand 3.3.3.3

Into the above script.

It all needs to be on one line as well, cannot use a stored script.

What I have tried:

Replacing the for loop with a while loop, like

myoutput | while read cmd; do... (and the rest of the script above on one line)

However it seems that when I use a while loop instead of the for loop, the $PID_LIST doesnt survive outside of the while loop. As its empty outside I cannot kill the processes after 20 seconds.

Do a while loop spawn a new sub-shell in another matter than the for loop? Or have I done something else when I replaced it?

Johnathan
  • 737
  • 2
  • 7
  • 21
  • 1
    You are basically reimplementing GNU `parallel`, which already handles command arguments more safely than you are and has a `--timeout` option to kill the commands after a specified number of seconds. – chepner Dec 22 '16 at 20:11
  • yeah, parallel isnt available on the system I am running the script on. – Johnathan Dec 22 '16 at 20:15
  • Do you know the [timeout](http://man7.org/linux/man-pages/man1/timeout.1.html) command? – Jdamian Dec 22 '16 at 20:29
  • yeah, but timeout isnt available as well on the system I am running this on. It is a hardened version of red hat linux. – Johnathan Dec 22 '16 at 20:33

0 Answers0