#前提已经可以通过mail或mutt客户端发邮件
1.先安装sendmail来发邮件
1
2
3
|
# yum -y install sendmail
# /etc/init.d/sendmail start
# chkconfig sendmail on
|
2.再安装邮件客户端
1
|
# yum -y install mutt
|
2.1 为了更好在邮件中显示,设置mutt客户端发送信息
1
2
3
4
5
6
7
|
# vim /etc/Muttrc
set
charset=
"utf-8"
#设置发邮件编码
set
envelope_from=
yes
set
rfc2047_parameters=
yes
#解决附件乱码问题
set
realname=
"报警"
#发件人别名
set
use_from=
yes
#指定是否显示别名
set
from=monitor@
test
.com
#发送人地址
|
方法1、通过加失败计数器来判断(误报率低)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#!/bin/bash
DATE=`
date
+%F
" "
%H:%M`
IP=
/root/monitor/ip
.txt
#ip地址表
MAIL=zhenliang369@163.com
for
ip
in
$(
cat
$IP |
sed
'/^#/d'
)
do
for
((i=1;i<=3;i++))
do
ping
-c 1 $ip &>
/dev/null
[ $? -
ne
0 ] &&
let
FailCount+=1;
done
done
[ -z $FailCount ] && FailCount=0
#当ping都正常时,FailCount值为空,就设置FailCount值为0,用整数比较
if
[ $FailCount -
eq
2 ];
then
#echo "$IP ping is failed."
echo
-e
"Date : $DATE\nHost : $ip\nProblem : Ping is failed, Please check ! ! !"
| mutt -s
"Ping Monitor"
$MAIL
fi
|
#添加任务计划
# crontab -e
*/1 * * * * /root/monitor/ping.sh
1
|
done
|
方法二、通过ping一个包的状态判断(误报率低,建议此方法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/bin/bash
MAIL=
"baojingtongzhi@163.com huangxiaohong@loongtao.com"
for
ip
in
$(
cat
ip_list|
sed
"/^#/d"
) #ip_list是当前目录下IP表
do
ping
-c 1 $ip &>
/dev/null
#三个ping有一个能通,说明服务器正常
a=$?
sleep
2
ping
-c 1 $ip &>
/dev/null
b=$?
sleep
2
ping
-c 1 $ip &>
/dev/null
c=$?
sleep
2
DATE=$(
date
+%F
" "
%H:%M)
if
[ $a -
ne
0 -a $b -
ne
0 -a $c -
ne
0 ];
then
echo
-e
"Date : $DATE\nHost : $ip\nProblem : Ping is failed."
| mail -s
"Ping $ip failed From 255.252"
$MAIL
#else
# echo "$ip ping is successful."
fi
done
|
方法三、通过丢包率来判断是否正常(误报率高)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/bin/bash
while
true
do
DATE=`
date
+%F
" "
%H:%M`
MAIL=
"zhenliang369@163.com"
for
ip
in
$(
cat
ip_list|
sed
"/^#/d"
) #ip_list是当前目录下IP表
do
num=$(
ping
-c 2 $ip |
grep
"100% packet loss"
|
wc
-l)
if
[ $num == 1 ];
then
echo
-e
"Date : $DATE\nHost : $i\nProblem : Ping is failed."
| mail -s
"Ping $i failed From 255.252"
$MAIL
fi
done
sleep
30
done
|
本文转自 李振良OK 51CTO博客,原文链接:http://blog.51cto.com/lizhenliang/1534285,如需转载请自行联系原作者