Shell

調試 Ping 腳本

  • December 16, 2018

之前請求過一個 ping 腳本的幫助,該腳本應該 ping 一些主機,如果任何 ping 失敗,請給我發電子郵件。這工作正常。

現在我想修改那個腳本(見下文),如果它成功了,它就會給我發電子郵件。所以基本上我希望腳本 ping 幾個我知道它們沒有啟動的主機,如果這些主機中的任何一個返回 ping,那麼我希望腳本通過電子郵件發送給我。這是我目前擁有的腳本:

#!/bin/bash

ping_targets="server1 server2 server3 server4 server5"
failed_hosts=""

for i in $ping_targets
do
  ping -c 1 $i > /dev/null
  if [ $? -ne 0 ]; then
     if [ "$failed_hosts" == "" ]; then
        failed_hosts="$i"
     else
        failed_hosts="$failed_hosts, $i"
     fi
  fi
done

if [ "$failed_hosts" != "" ]; then
  echo $failed_hosts| mailx -s "Failed ping targets" email@domain
fi
#!/bin/bash

ping_targets="server1 server2 server3 server4 server5"

for i in $ping_targets
do
  ping -c 1 $i > /dev/null
  if [ $? -eq 0 ]; then
        echo "$i ping success!" > test_file
  fi
  if [ -s test_file ];then        
        mailx -s "Successful ping targets" -a test_file email@domain
  fi

如果您不想添加附件,請將mailxline 替換為:

mailx -s "Successful ping targets" email@domain < test_file
ping_targets="server1 server2 server3 server4 server5"
up_hosts=""

for i in $ping_targets
do
  ping -c 1 $i > /dev/null
  if [ $? -eq 0 ]; then
     if [ "$up_hosts" == "" ]; then
        up_hosts="$i"
     else
        up_hosts="$up_hosts, $i"
     fi
  fi
done

if [ "$up_hosts" != "" ]; then
  echo $up_hosts| mailx -s "ping targets that are now available" email@domain
fi

引用自:https://unix.stackexchange.com/questions/347102