电子邮件警报和 ping 脚本

Vik*_*tso 3 email bash

我需要帮助更新这个脚本,如果 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
Run Code Online (Sandbox Code Playgroud)

oli*_*bre 5

你可以把这些ping东西放在一个函数中。您不需要处理 ( grep)ping结果:您可以依靠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
Run Code Online (Sandbox Code Playgroud)