pingmany, simple bash script to ping a bunch of hosts

It came up twice that I had to do this, so I decided to see if I could make something simple that solved my problem. I'm sure there's a project to do this already, but here goes. I have a list of machines, I want to see if they respond to a ping so I can determine if they are up or not.

I wanted to do this two ways, either by feeding in a list from stdin or by giving hostnames as arguments. This took a few revisions to get just right, but here's what I came up with:


#!/bin/bash
# ping many hosts and return up or down for each

usage () {
echo "Ping Many Hosts"
echo "Usage: $0 host1 [host2 host3]"
echo "echo host1 | $0"
echo "ping all hosts, return up or down for each"
}
# read hostnames from stdin or command line arguments
if [ $# -eq 0 ]; then
#hosts=$(cat /dev/stdin)
read -t 2 hosts
else
hosts="$*"
fi

if [ "$hosts" == "" ]; then
usage
exit 1
fi
fail=0
# loop over hosts, ping once, wait 1 second
for host in $hosts
do
echo -n "$host "
ping -c 1 -t 1 -q $host >/dev/null 2>&1
if [ $? == 0 ]; then
echo up
else
echo down
# return a fail for the whole run if you can't reach any of the hosts
fail=1
fi
done
exit $fail

The secret sauce is giving the timeout to read, so that if you don't give any input, it gives up after the timeout and gives you the usage information.
Now I have to do the same thing with netcat for a specific port, of course the port would be an argument, so I'll need to modify the logic to make that work too...

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

About the Author...

Slides from LISA 2019 Linux systems troubleshooting #LISA2019 https://t.co/D4dMKflK6R Tue Oct 29 05:59:30 +0000 2019

https://t.co/AGeihMALAv configuring grub2 with EFI Fri Sep 13 05:20:01 +0000 2019

I published a Thing on @thingiverse! https://t.co/IYpRyEb7Hz #thingalert Tue Jul 23 19:27:57 +0000 2019

Nokogiri install on MacOSX https://t.co/v3An0miW9L Fri Jul 12 15:06:49 +0000 2019

HTML email with plain mailer plugin on Jenkins https://t.co/Z6FSDMDjy8 Thu Jul 11 21:07:25 +0000 2019