Quantcast
Channel: Ping hosts based on filter and return dead or alive - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 3

Answer by sebasth for Ping hosts based on filter and return dead or alive

$
0
0

You can use the exit code from ping to determine if ping succeeded or failed.

ping HOST -c1 > /dev/null && echo "ALIVE" || echo "DEAD"

When host is alive exit code is 0, and for dead 1. To ping every host you can loop each line and use awk to get the first column which contains address/hostname.

exec 3<input.txt

while read -u3 line
do
    if [ "$line" == "" ]; then
        # skip empty lines
        continue
    fi

    ping -c1 $(echo "$line"| awk '{print $1}') > /dev/null

    if [ $? = 0 ]; then
        echo "$line=ALIVE"
    else
        echo "$line=DEAD"
    fi
done

EDIT:

If you want only to ping host by matching a single line in the file, you can grep it:

# find line for $host, only 1 line
line = grep "$HOST" input.txt |tail -n 1

# $($line |awk '{print $1}') outputs the first column of line (address)
ping -c1 $($line |awk '{print $1}') >/dev/null && echo "$line=ALIVE" || echo "$line=DEAD"

Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>