美文网首页Python新世界python热爱者
黑白之道,Python监控服务器实现邮件、微信报警!

黑白之道,Python监控服务器实现邮件、微信报警!

作者: 48e0a32026ae | 来源:发表于2018-12-08 15:44 被阅读2次

    本文中笔者暂时实现的只有cpu和内存的监控,python可以监控许多的主机信息,网络,硬盘,机器状态等,以下是代码的实现,代码可以实现windows和linux的监控

    学习Python中有不明白推荐加入交流群

                    号:516107834

                    群里有志同道合的小伙伴,互帮互助,

                    群里有不错的学习教程!

    实验环境:Ubuntu16.04和windos10,python3.6.6

    import psutil, time

    import datetime

    from wechatpy import WeChatClient

    class Monitor():

    cpu_data = []

    @classmethod

    def mem(cls, max=90):

    val = psutil.virtual_memory().percent

    if val > max:

    cls.send_msg('内存使用率为{:1.f}%,超过了{}%,请关注'.format(val, max))

    @classmethod

    def cpu(cls, max=90):

    val = psutil.cpu_percent(1)

    cls.cpu_data.append(val)

    if len(cls.cpu_data) >= 3:

    avg = sum(cls.cpu_data) / len(cls.cpu_data)

    if avg > max:

    cls.send_msg('CPU使用率为{:1f}%,超过了{}%,请关注'.format(avg, max))

    cls.cpu_data.pop(0)

    @classmethod

    def send_msg(cls, content):

    cls.mail(content)

    cls.wechat(content)

    @classmethod

    def mail(cls, content):

    import smtplib

    from email.mime.text import MIMEText

    from email.utils import formataddr

    nickname = '监控程序'

    # 发送者的信息

    sender = 'xxx@qq.com'

    password = '*****'

    # 接收方的邮箱

    receiver = 'aa@bb.cc'

    msg = MIMEText(content, 'html', 'utf-8')

    msg['From'] = formataddr([nickname, sender])

    msg['Subject'] = '自动报警'

    server = smtplib.SMTP_SSL('smtp.qq.com', 465)

    try:

    server.login(sender, password)

    server.sendmail(sender, [receiver], msg.as_string())

    except Exception as ex:

    print(ex)

    finally:

    server.quit()

    @classmethod

    def wechat(cls, content):

    client = WeChatClient('xxxx', 'xxxx')

    template_id = 'xxxxx'

    openid = 'xxxx'

    data = {

    'msg': {"value": content, "color": "#173177"},

    'time': {"value": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "color": "#173177"},

    }

    try:

    client.message.send_template(openid, template_id, data)

    except Exception as ex:

    print(ex)

    while True:

    Monitor.mem(90)

    Monitor.cpu(90)

    time.sleep(5)

    下面是qq邮箱和微信实现报警的图片:

    qq邮箱:

    微信报警:

    以上就是所有的代码了,谢谢

    相关文章

      网友评论

        本文标题:黑白之道,Python监控服务器实现邮件、微信报警!

        本文链接:https://www.haomeiwen.com/subject/qzpqhqtx.html