Bash ping status script

ⅰ亾dé卋堺 提交于 2020-01-24 00:47:06

问题


I've done the following script

HOSTS="ns1.server.com ns2.server.com"
SUBJECT="Host Down"

for myHost in $HOSTS
do
count=$(ping -c 10 $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{               
print $1 }')
if [ $count -eq 0 ]; then
echo "Host : $myHost is down (ping failed) at $(date)" | sendEmail -f email (email address removed) -u "$SUBJECT" etc etc
fi
done

Run via cron every 5 minutes however when a host is down I will receive and email every 5 minutes reflecting this. What i'd like is to add the function so that it only emails me when the status has changed. ie if it's down I don't want it to send any further updates until it's up.


回答1:


I think something like this can help:

#!/bin/bash

HOSTS="ns1.server.com ns2.server.com"
HOSTS="123.123.1.1 ns1.server.com"
SUBJECT="Host Down"

ping_attempts=1
down_hosts=down_hosts.txt

for myHost in $HOSTS
do
        count=$(ping -c $ping_attempts $myHost | awk -F, '/received/{print $2*1}')
        echo $count
        if [ $count -eq 0 ]; then
                echo "$myHost is down"
                if  [ $(grep -c "$myHost" "$down_hosts") -eq 0 ]; then
                        echo "Host : $myHost is down (ping failed) at $(date)"
                        echo "$myHost" >> $down_hosts
                fi
        else
                echo "$myHost is alive"
                if  [ $(grep -c "$myHost" "$down_hosts") -eq 1 ]; then
                        echo "Host : $myHost is up (ping ok) at $(date)"
                        sed -i "/$myHost/d" "$down_hosts"
                fi
        fi
done



回答2:


There is a good point in the comments that you might want to use an infinite loop. But as you have asked for something different, here you go:

HOSTS="ns1.server.com ns2.server.com"
SUBJECT="Host Down"
PATH_STATUS='/yourfolder/hoststatus_' # For example can be located in /tmp.

for myHost in $HOSTS; do
    count=$(ping -c 10 "$myHost" | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
    [[ -f "$PATH_STATUS$myHost"]] && prevStatus=$(cat "$PATH_STATUS$myHost") || prevStatus='unknown'
    [[ $count == 0 ]] && curStatus='down' || curStatus='up'

    if [[ $curStatus != $prevStatus ]]; then
        echo "$curStatus" > "$PATH_STATUS$myHost"
        echo "Host : $myHost is $curStatus at $(date)" | sendEmail
    fi
done


来源:https://stackoverflow.com/questions/18378941/bash-ping-status-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!