用于电子邮件警报和ping的脚本

时间:2012-01-18 22:04:55

标签: bash email

我需要帮助才能更新此脚本,如果ping失败,它会向另一台主机发送另一个ping(除了ping失败后立即发送的电子邮件)。 如何从这个脚本完成?

#!/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" myadress@gmail.com
        echo "Host : $myHost is down (ping failed) at $(date)"
    fi
done

2 个答案:

答案 0 :(得分:3)

您可以将ping内容放入函数中。您无需处理(grepping结果:您可以依赖ping返回退出状态。

#!/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" myadress@gmail.com
  echo "All hosts ($HOSTS) are down (ping failed) at $(date)"
fi

答案 1 :(得分:-3)

尝试使用数组:

#!/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" myadress@gmail.com
         echo "Host : $myHost is down (ping failed) at $(date)"
     fi
done