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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8918159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:21:21  来源:igfitidea点击:

Script for email alert and ping

bashemail

提问by Viktor Kuznyetso

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?

我需要帮助更新这个脚本,如果 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  }' | 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

回答by olibre

You can put the pingstuff in a function. You do not need to process (grep) the pingresult: you can rely on pingreturn exit status.

你可以把这些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" [email protected]
  echo "All hosts ($HOSTS) are down (ping failed) at $(date)"
fi

回答by Zsolt Botykai

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  }' | 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