0

我已经完成了以下脚本

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

每 5 分钟通过 cron 运行一次,但是当主机关闭时,我将每 5 分钟收到并通过电子邮件反映这一点。我想要的是添加该功能,以便它仅在状态更改时向我发送电子邮件。即,如果它关闭了,我不希望它在它启动之前发送任何进一步的更新。

4

2 回答 2

1

我认为这样的事情可以提供帮助:

#!/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
于 2013-08-22T11:58:52.783 回答
0

评论中有一个很好的观点,您可能想要使用无限循环。但是,由于您要求不同的东西,所以您可以:

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
于 2013-08-22T11:47:02.020 回答