Reputation: 57
I need help to update this script to if ping fails it would send another ping to another host (besides the email which is sent now if ping fails). How can this be done from this script?
#!/bin/bash
HOSTS="IP ADRESS"
COUNT=4
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | a$
if [ $count -eq 0 ]; then
# 100% failed
echo "Server failed at $(date)" | mail -s "Server Down" [email protected]
echo "Host : $myHost is down (ping failed) at $(date)"
fi
done
Upvotes: 3
Views: 23670
Reputation: 54561
You can put the ping
stuff in a function. You do not need to process (grep
) the ping
result: you can rely on ping
return exit status.
#!/bin/bash
HOSTS="IP1 IP2 IP3 IP4 IP5"
COUNT=4
pingtest(){
for myHost in "$@"
do
ping -c "$COUNT" "$myHost" && return 1
done
return 0
}
if pingtest $HOSTS
then
# 100% failed
echo "Server failed at $(date)" | mail -s "Server Down" [email protected]
echo "All hosts ($HOSTS) are down (ping failed) at $(date)"
fi
Upvotes: 5
Reputation: 51613
Try this with an array:
#!/bin/bash
HOSTS_ARRAY=("IP_ADRESS" "ANOTHER_IP" "YET_ANOTHER")
COUNT=4
for myHost in "${HOSTS_ARRAY[@]}"
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | a$
if [ $count -eq 0 ]; then
# 100% failed
echo "Server failed at $(date)" | mail -s "Server Down" [email protected]
echo "Host : $myHost is down (ping failed) at $(date)"
fi
done
Upvotes: -3