Bash script to detect nonpingable hosts

I have a script to detect if a host is pingable or not. The problem is that I would like it to put the nonpingable hosts in one file and the pingable hosts in another. I have come up with this so far:

for ip in `cat /tmp/testlist2`; do ping -c 3 $ip >/dev/null && echo "$ip is up" || echo "$ip is down"; done>/tmp/s4.file
cat /tmp/s4.file |grep -i down >/tmp/f1.file
cat /tmp/s4.file |grep -i up >/tmp/sup.file

This works but it is clumsy. If I try to just do a redirect after the ping it doesn't work, though. What I get is only the first host name that the ping is tried on. Would I need another loop to get the hosts in two different files? Any suggestions?

Here is a port of ping test I did make some time ago, maybe you can use it.

[[ "$(ping -c 1 -w 192.168.0.33 | awk '/received / {print $4}')" == "0" ]] && echo "nok" || echo "ok"

Example: You can change output of up/down to separete files if you like

#!/bin/bash
for ip in $(cat /tmp/testlist2); do
        if [[ "$(ping -c 1 -w 1 $ip | awk '/received/ {print $4}')" == "0" ]]
        then
                echo "$(date) $ip is down" >> /tmp/log
        else
                echo "$(date) $ip is up" >> /tmp/log
        fi
done
1 Like

You could try something like:

rm -f /tmp/f1.file /tmp/sup.file
for ip in $(cat /tmp/testlist2)
do      ping -c 3 $ip >/dev/null && echo "$ip is up" >> /tmp/sup.file || echo "$ip is down" >> /tmp/f1.file
done
1 Like

A bit more elegant, store only hosts:

file=/tmp/testlist2
while read ip
do
 ping -c 3 $ip >/dev/null &&
 echo $ip
done < $file > $file.up
fgrep -vxf $file.up $file > $file.down

One snag in that post MadeInGermany.

Hosts that are a substring of others will cause mismatch with grep (eg DEV and DEV01)

And therefore the -x option!
Another variant with descriptor magic:

file=/tmp/testlist2
while read ip
do
 ping -c 3 $ip >/dev/null &&
 echo $ip ||
 echo $ip >&3 
done < $file > $file.up 3> $file.down
1 Like