Need a Simple ping script

Hi,

I am a learner in shell scripting. Can someone help me in getting a script to run the ping command in the background through a script to get the status of my servers and email me if ping failed with list of servers in one email.

Thanks

do you have something in your mind?

man ping

ping switches varies with OS. what flavor you have?

try something;

while read HOST
do
 ping $HOST
 if [ "$?" -ne "0" ]; then
  echo $HOST >> failed_host.$$
 fi
done < hostfile
if [ -s "failed_host.$$"];then
 cat failed_host.$$ | mailx -s failed server list somename@domain.com
fi

note: this is just an idea. not tested.

Thanks for the response.

I have couple of hosts in the same network running on Solaris and Linux. Ping command varies from solaris and linux. We need a script to grep for uname first,then if it returns solaris i am using " `ping -s $myHost $SIZE $COUNT | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }'`" . If uname returns linux then " (ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')". My question is if i run the ping for single host it takes min 10secs for the 4 packets to transmit. I need help in writing the script which executes the ping at background on all hosts and write to a file. Then parse the for "recieved -eq 0" then shoot an email with the ping failed hosts.

myHost = /home/user/listofhosts -- file stored with list of hosts(linux&solaris)

ping -c 3 $SERVER

so it will stop after 3 pings

This simple script should do the trick:

#!/bin/ksh
HOSTLIST=~/hostlist
rm /tmp/pingfail.* 2>/dev/null
for host in $(cat $HOSTLIST); do
  ( ping -c 4 $host >/dev/null 2>&1 || touch /tmp/pingfail.$host)&
done;
wait
if ls /tmp/pingfail.*>/dev/null 2>&1; then
  for failhost in /tmp/pingfail.*; do
    echo ${failhost#*.}
  done | mailx -s "failed server list" somename@domain.com 2>/dev/null
  rm /tmp/pingfail.* 2>/dev/null
fi

Instead of ksh you can use bash too, just replace #!/bin/ksh with #!/bin/bash

1 Like