Let us start with 1.: Because commands in a script are only processed sequentially you will have to send the jobs in the background to have them run concurrently:
while read chHost ; do
ping "$chHost" &
done < hosts.txt
is quite simple, just add a redirection:
while read chHost ; do
# ping "$chHost" > "$chHost".log & # create new logfile every run
ping "$chHost" >> "$chHost".log & # append to existing log
done < hosts.txt
For 3. set up a second loop:
while : ; do
while read chHost ; do
nmap -sP $chHost >> ${chHost}-nmap.log
done < hosts.txt
sleep 30
done
That leaves the starting/stopping issue. I'd use a PID file in "/var/run" and use that to eliminate the process:
#! /bin/ksh
DispHostList ()
{
typeset chHost=""
while reach chHost ; do
print - "$chHost"
done < /path/to/hosts.txt
return 0
}
pStop ()
{
typeset fPID="$1"
if [ ! -e "$fPID" ] ; then
print -u2 "ERROR: there is nothing to stop"
exit 1
else
kill -15 "$(cat "$fPID")"
fi
return 0
}
pStart ()
{
typeset PID="$$"
typeset chHost=""
typeset fPID="$1"
if [ -e "$fPID" ] ; then
print - u2 "ERROR: another instance seems to run."
exit 1
else
print - "$PID" > "$fPID"
fi
DispHostList |\
while read chHost ; do
# ping "$chHost" > "$chHost".log & # create new logfile every run
ping "$chHost" >> "$chHost".log & # append to existing log
done
while : ; do # this will loop forever
DispHostList |\
while read chHost ; do
nmap -sP $chHost >> ${chHost}-nmap.log
done
sleep 30
done
}
# main()
typeset fRun="/var/run/pinglog.pid"
case "$1" in
start)
pStart "$fRun"
;;
restart)
pStop "$fRun"
pStart "$fRun"
;;
stop)
pStop "$fRun"
;;
*)
print -u2 "ERROR: do not know how to handle \"$1\""
exit 1
;;
esac
exit 0
So, I had gotten close to the list thing stumbling through, but essentially took your advice verbatim and did the following:
#!/bin/bash
#while read chHost ; do
# ping "$chHost" &
#done < hosts.txt
while read chHost ; do
# ping "$chHost" > "$chHost".log & # Create new log ever run
ping "$chHost" | xargs -n1 -i bash -c 'echo `date +"%m-%d %H:%M:%S"`" {}"' >> ./Ping/"$chHost".log &
done < hosts.txt
Which works great. But I noticed it was a bear to try and do any sort of PS since it spawned so many. The second PID portion of your suggestion REALLY has my head spinning and thus I'll need to re-read it.
So, in the meantime, I've just adjusted the script to do the following (which is probably a better I idea anyway)
As much as i would like to take the praise for this idea: it is common within many UNIX programs (daemons mostly) to create a file with the PID (process ID) in /var/run at the start and use the PID stored there to shut down the process.