pyton3+shell监控系统cpu阀值邮件报警

一个简单轻量的监控脚本,
使用shell脚本获取用户态cpu百分比,使用crontab定时执行监控,超过设置的阀值使用python3代码邮件报警

crontab:

0 */1 * * * /usr/local/cpu_alarm.sh

一分钟执行一次,时间可以自己调整

shell:

#/bin/bash
bu=`free | awk 'NR==2{print $6}'`
to=`free | awk 'NR==2{print $2}'`
mem=`top -b -n 1 | grep Cpu | awk '{print $2}' | bc -l | cut -d. -f1`
echo $mem
if(($mem >= 70))
        then
        msg="TIME:$(date +%F_%T)
                 HOSTNAME:$(hostname)
                 IPADDR:$(ifconfig |awk 'NR==2{print $2}')
                 MSG:内存high了high了!已经用了${mem}%"
            echo $msg
        /usr/bin/python3 /usr/local/mail_alarm.py  $msg
fi

python3邮件报警代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.utils import parseaddr, formataddr

# 邮件配置
email = False                    # 开启邮件通知功能
variable = {
    # email parameter
    'smtp_server': 'smtp.exmail.qq.com',
    'from_address': 'wang.lulu@.cn',
    'password': 'Wang566',
    # 收件人信息
    'to_address': 'wang.lulu@.cn',
    #'to_address': 'wang.lulu@cn',
    'cc_address': '',
    'mail_text': 'Scripts Program exec complete ',
    'title': '脚本程序已运行'
}


class Send_Mail(object):
    def __init__(self, text=variable['mail_text'], filename='', title=variable['title']):
        # 发件人
        self.from_addr = variable['from_address']
        # 发件人密码
        self.password = variable['password']
        # 收件人列表
        self.to_addr = [x.strip() for x in variable['to_address'].split(';')]
        self.Cc_addr = [x.strip() for x in variable['cc_address'].split(';')]
        # 邮件主题
        self.mail_title = title
        self.smtp_server = variable['smtp_server']
        self.mail_text = text
        self.filename = filename

    @staticmethod
    def __format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    def __sendmail(self):
        self.msg = MIMEMultipart()
        self.msg.attach(MIMEText('%s' % self.mail_text, 'plain', 'utf-8'))

        self.msg['From'] = self.__format_addr('Python Program <%s>' % self.from_addr)
        self.msg['To'] = ';'.join(self.to_addr)
        self.msg['Cc'] = ';'.join(self.Cc_addr)
        self.msg['Subject'] = Header(self.mail_title, 'utf-8').encode()

        self.mime = MIMEBase('text', 'xlsx', filename=os.path.split(self.filename)[-1])
        self.mime.add_header('Content-Disposition', 'attachment', filename=os.path.split(self.filename)[-1])
        self.mime.add_header('Content-ID', '<0>')
        self.mime.add_header('X-Attachment-Id', '0')
        if os.path.isfile(self.filename):
            with open(self.filename, 'rb') as f:
                print('开始读取附件...')
                self.mime.set_payload(f.read())
            encoders.encode_base64(self.mime)
            self.msg.attach(self.mime)
        try:
            print("开始解析邮件服务器信息")
            server = smtplib.SMTP_SSL(self.smtp_server, 465)
            # server.set_debuglevel(1)
            print("开始登录到smtp服务器")
            server.login(self.from_addr, self.password)
            print("登录到SMTP服务器成功开始发送邮件")
            server.sendmail(self.from_addr, self.to_addr, self.msg.as_string())
            server.close()
        except smtplib.SMTPAuthenticationError:
            print("登录到smtp服务器失败, 无法发送邮件")
        except Exception as err:
            print('邮件发送失败\nError:\n' + str(err) + '\n\nHeader:\n' + self.msg.as_string())
        else:
            print("邮件已成功发送到%s" % self.to_addr)

    def send(self):
        self.__sendmail()

if __name__ == '__main__':
    content = '%s\n%s' % ('\n'.join(sys.argv[1:4]), ' '.join(sys.argv[4:]))  # 格式处理,专门针对我们的邮件格式
    mail = Send_Mail(text=content, title="服务器报警请注意!",filename="")
    mail.send()

你可能感兴趣的