• 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 #每分钟执行一次这个脚本

  • 相关阅读:
    scrapy框架
    003-更改pip的源让下载安装更加快捷
    日志,序列反序列和正则表达式
    菜鸟的IT生活4
    IT菜鸟的3(for循环+分支语句)
    IT菜鸟的第2天(输入输出,数据类型,运算符的使用)
    IT菜鸟的第一天
    第二课笔记
    第一节课预习笔记
    第一节课作业
  • 原文地址:https://www.cnblogs.com/hanhan914-wang/p/7290912.html
Copyright © 2020-2023  润新知