服务器性能监控shell脚本
通过python编写邮件发送工具,通过shell编写性能采集工具进行发现,邮件告警。
1.python邮件脚本
#!/usr/bin/python # -*- coding: UTF-8 -*- import sys import smtplib import email.mime.multipart import email.mime.text server = 'smtp.163.com' port = '25' def sendmail(server,port,user,pwd,msg): smtp = smtplib.SMTP() smtp.connect(server,port) smtp.login(user, pwd) smtp.sendmail(msg['from'], msg['to'], msg.as_string()) smtp.quit() print('邮件发送成功email has send out !') if __name__ == '__main__': msg = email.mime.multipart.MIMEMultipart() msg['Subject'] = '服务器监控测试邮件' msg['From'] = 'xxx@163.com' msg['To'] = 'xxx@qq.com' user = 'xxx' pwd = 'xxxxxxxxx' content='%s\n%s' %('\n'.join(sys.argv[1:4]),' '.join(sys.argv[4:])) #格式处理,专门针对我 们的邮件格式 txt = email.mime.text.MIMEText(content, _charset='utf-8') msg.attach(txt)
将脚本拷贝至/usr/bin/mail,并授予执行权限chmod +x /usr/bin/mail
2.shell 监控脚本(内存示例)
#! /bin/bash mem_limit=0 #内存使用超过90%则报警,为了测试效果,数值为0 function monitor_mem(){ mem_total=`free |awk 'NR==2{print $2}'` mem_use=`free |awk 'NR==2{print $3}'` mem_per=`echo "scale=2;$mem_use/$mem_total" |bc -l|cut -d. -f2` #bc&&cut详解 参照下文 if [ $mem_per -gt $mem_limit ] then msg="TIME:$(date +%F_%T) HOSTNAME:$(hostname) IPADDR:$(ifconfig |awk 'NR==2{print $2}') MSG:Memory usage exceeds the limit,current value is ${mem_per}%" echo $msg /usr/bin/mail $msg fi } monitor_mem &>> /tmp/monitor.log
3.设置计划任务
* * * * * /root/shell/check.sh
测试结果