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 #每分钟执行一次这个脚本
posted on 2017-08-05 17:44 hanhan914wang 阅读(185) 评论(0) 收藏 举报
 
                    
                     
                    
                 
                    
                 
                
            
         
 
         浙公网安备 33010602011771号
浙公网安备 33010602011771号