pingmany, simple bash script to ping a bunch of hosts

By thomas, 16 September, 2015

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:

# 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

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