zoukankan      html  css  js  c++  java
  • 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 %s' %(' '.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 #每分钟执行一次这个脚本

  • 相关阅读:
    现存的数据库的解决方案的原理解析
    HTTP代理实现请求报文的拦截与篡改
    ucos软件结构
    微软官方Windows 8设计
    asp.net对CNMARC
    jQuery弹出层插件
    从"Hello World!"到面向对象
    git 的使用命令:克隆
    第一个C程序
    云计算平台简介(App Engine)
  • 原文地址:https://www.cnblogs.com/hanhan914-wang/p/7290912.html
Copyright © 2011-2022 走看看