Code:
$ cat ssh.sh
#!/bin/bash
MAXPROCS=2
PROCS=$(seq 1 $MAXPROCS)
function ssh_hosts # Reads hosts from stdin, writes output to stdout
{
while read HOST
do
ssh "$HOST" printf "$HOST" ';' uptime </dev/null
done
}
# Loop until we run out of lines
while [ -z "$FINISHED" ]
do
# Read a line for each thread and feed it into the right file
for N in $PROCS
do
if read LINE
then
echo "$LINE">>/tmp/$$-$N
continue
fi
FINISHED=1
break
done
done < hosts1
for N in $PROCS
do
# Add these to the list of tempfiles to delete on exit
FILES="$FILES /tmp/$$-out$N /tmp/$$-$N"
# Make a process reading from /tmp/$$-$N and writing to /tmp/$$-out$N
ssh_hosts < /tmp/$$-$N > /tmp/$$-out$N &
done
# Delete all temporary files on exit, even if we quit with ctrl-c
trap "rm -f $FIFOS $FILES" EXIT
wait # Wait for readers to quit
cat /tmp/$$-out* # Read all output to stdout
$ cat hosts1
172.16.0.154
172.16.0.62
172.16.0.222
172.16.0.182
172.16.0.90
172.16.0.226
172.16.0.118
172.16.0.158
172.16.0.50
172.16.0.130
172.16.0.86
$ ./ssh.sh
172.16.0.154 11:10:32 up 6 days, 21:36, 0 users, load average: 0.01, 0.02, 0.00
172.16.0.222 11:18:44 up 15 days, 21:26, 0 users, load average: 0.03, 0.03, 0.00
172.16.0.90 10:50:28 up 2 days, 26 min, 0 users, load average: 0.06, 0.04, 0.00
172.16.0.118 11:04:55 up 12 days, 23:12, 0 users, load average: 0.11, 0.07, 0.02
172.16.0.50 10:51:34 up 47 days, 19:47, 0 users, load average: 0.04, 0.04, 0.00
172.16.0.86 11:02:14 up 22 days, 1:52, 0 users, load average: 0.01, 0.01, 0.00
172.16.0.62 11:24:51 up 21 days, 2:27, 0 users, load average: 0.00, 0.00, 0.00
172.16.0.182 10:15:50 up 2 days, 25 min, 0 users, load average: 0.02, 0.04, 0.00
172.16.0.226 11:17:48 up 6 days, 21:37, 0 users, load average: 0.00, 0.00, 0.00
172.16.0.158 11:21:46 up 2 days, 24 min, 0 users, load average: 0.08, 0.02, 0.01
172.16.0.130 10:57:22 up 5 days, 19:42, 0 users, load average: 0.00, 0.00, 0.00
$