我问之前寻求 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
答案1
#!/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
如果您不想添加附件,请将mailx
行替换为:
mailx -s "Successful ping targets" email@domain < test_file
答案2
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
答案3
使用fping检查多台服务器的ping:
fping server{1,2,3,4,5} |& grep -v 'is alive' | mailx -E -s "Failed ping targets" email@domain