准备工作
在将要监控的服务器上下载mailx sendmail
yum -y install mailx sendmail
更改配置文件
vi /etc/mail.rc
在其后添加
set from=xxxx@qq.com
set smtp=smtp.qq.com
set smtp-auth-user=xxxxxxx@qq.com
set smtp-auth-password=dpsoosljfdjedfae(此处应填写SMTP授权码)
set smtp-auth=login
新建一个shell脚本
远程连接服务器
ssh -p $dk
u
s
e
r
n
a
m
e
@
user_name@
username@id
shell小脚本
#!/bin/bash
while true
do
read -p "请选择(0.退出 1.查询):" n
case $n in
0)
echo "欢迎下次查看"
break
;;
1)
read -p "输入用户名:" user
read -p "输入服务器ip地址:" ip
read -p "输入服务器端口号:" dh
echo "1.查看CPU利用率 2.查看磁盘可用容量 3.查看内存可用量"
read -p "请选择:" n
cpu_u=0.1
disk=500
mem=10
ssh -p $dh $user@$id
case $n in
1)
#cpu利用率
cpu=`top -n 1 | awk -F '[ %]+' 'NR==3 {print $3}'`
if [ $cpu > $cpu_u ]
then
echo "CPU利用率过高!!!"
fi
;;
2)
#磁盘可用空间
disk_free=`df -h |grep 'dev/sda1'|awk -F '[ M]+' '{print $4}'`
if [ $disk_free -le $disk ]
then
echo "磁盘可用空间太少"
fi
;;
3)
mem_used=`free -h | awk -F ' ' 'NR==2 {print $2}'`
#物理内存可用大小
mem_free=`free -h | awk -F ' ' 'NR==3 {print $2}'`
if [ $mem_free -le $mem ]
then
echo "物理内存剩余太少"
fi
;;
*)
;;
esac
#发报警邮件
send_mail(){
read -p '邮件账号:' user
read -p '邮件类型:' type
mail -s "监控报警" $user@$type < send.log
}
#报警判断函数
control(){
if [[ $cpu > $cpu_u ]] || [[ $disk_free -le $disk ]] || [[ $mem_free -le $mem ]]
then
now_time=`date '+%F %T'`
echo "报警时间: $now_time" >> send.log
echo -e "CPU使用率(%): ${cpu} \n 磁盘剩余空间(M):${disk} \n 物理内存剩余(G):${mem}" >> send.log
send_mail
fi
}
#主函数
main(){
control
}
main
;;
*)
echo "没有此选项"
;;
esac
done