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...

Wordpress category: 

Comments

You might want to have a look at going which does something similar but pings the targets in parallel.
Paul

Thanks, my friend pointed it out, worked for me too.

Add new comment

Markdown

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.