黑白之道,Python監控伺服器實現郵件、微信報警!
阿新 • • 發佈:2018-12-09
本文中筆者暫時實現的只有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 = '
[email protected]' password = '*****' # 接收方的郵箱 receiver = '[email protected]' 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郵箱:
微信報警:
以上就是所有的程式碼了,謝謝