shell脚本编写监控内存并发送邮件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell脚本编写监控内存并发送邮件相关的知识,希望对你有一定的参考价值。

1.准备发送邮件的工具:

#!/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‘] = ‘发送的邮箱‘
msg[‘To‘] = ‘接收的邮箱‘
user = ‘用户‘
pwd = ‘密码‘
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)

sendmail(server,port,user,pwd,msg)

2.将上述文件内容拷贝到/usr/bin/mail并chmod+x /usr/bin/mail

3.然后新建脚本servermonitor.sh

#!/bin/bash
mem_limit=0 #内存使用超过90%则报警

function monitor_mem(){
mem_total=`free |awk ‘NR==2{print $2}‘`
mem_user=`free |awk ‘NR==2{print $3}‘`
mem_per=`echo "scale=2;$mem_user/$mem_total" |bc -l|cut -d. -f2`
if [ $mem_per -gt $mem_limit ]
then
msg="TIME:$(data +%F_%T)
HOSTNAME:$(hostname)
IPADDR:$(ifconfig |awk ‘NR==18{print $2}‘|awk -F: ‘{print $2}‘)
MSG:Memory usage exceeds the limit,current value is ${mem_per}%"
echo $msg
/usr/bin/mail $msg
fi
}
monitor_mem &>> /root/wang/monitor.log

 

4.编写计划任务:

* * * * * /root/servermonitor.sh #每分钟执行一次这个脚本


































以上是关于shell脚本编写监控内存并发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

编写监控脚本,监控集群内所有服务存活状态,内存磁盘剩余率检测,异常则发送报警邮件

简单监控liunx中cpu内存磁盘及发送邮件参考

Linux下监控磁盘使用量并在超过阀值后自动发送报警邮件

一个检查分区内存并且发送邮件的shell脚本

开放系统监控shell脚本

Day11.开发脚本自动部署及监控