0

I asked before for help with a ping script that should ping some hosts and email me if it any ping fails. This works fine.

Now I want to modify that script (see below) so it emails me if it succeeded only. So basically I want the script to ping few hosts I know they're not up and if any of those hosts returned ping, then I want the script to email me. Here's the script I currently have:

#!/bin/bash

ping_targets="server1 server2 server3 server4 server5"
failed_hosts=""

for i in $ping_targets
do
   ping -c 1 $i > /dev/null
   if [ $? -ne 0 ]; then
      if [ "$failed_hosts" == "" ]; then
         failed_hosts="$i"
      else
         failed_hosts="$failed_hosts, $i"
      fi
   fi
done

if [ "$failed_hosts" != "" ]; then
   echo $failed_hosts| mailx -s "Failed ping targets" email@domain
fi
0
0
#!/bin/bash

ping_targets="server1 server2 server3 server4 server5"

for i in $ping_targets
do
   ping -c 1 $i > /dev/null
   if [ $? -eq 0 ]; then
         echo "$i ping success!" > test_file
   fi
   if [ -s test_file ];then        
         mailx -s "Successful ping targets" -a test_file email@domain
   fi

If you don't want to add attachment, replace mailx line with:

mailx -s "Successful ping targets" email@domain < test_file
0
0
ping_targets="server1 server2 server3 server4 server5"
up_hosts=""

for i in $ping_targets
do
   ping -c 1 $i > /dev/null
   if [ $? -eq 0 ]; then
      if [ "$up_hosts" == "" ]; then
         up_hosts="$i"
      else
         up_hosts="$up_hosts, $i"
      fi
   fi
done

if [ "$up_hosts" != "" ]; then
   echo $up_hosts| mailx -s "ping targets that are now available" email@domain
fi
0
-1

Use fping to check ping of multiple servers:

fping server{1,2,3,4,5} |& grep -v 'is alive' | mailx -E -s "Failed ping targets" email@domain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.