内容简介:本文中笔者暂时实现的只有cpu和内存的监控,python可以监控许多的主机信息,网络,硬盘,机器状态等,以下是代码的实现,代码可以实现windows和linux的监控。实验环境:Ubuntu16.04和windos10,python3.6.6
本文中笔者暂时实现的只有cpu和内存的监控,python可以监控许多的主机信息,网络,硬盘,机器状态等,以下是代码的实现,代码可以实现windows和 linux 的监控。
实验环境: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监控服务器实现邮件微信报警》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming Python
Mark Lutz / O'Reilly Media / 2006-8-30 / USD 59.99
Already the industry standard for Python users, "Programming Python" from O'Reilly just got even better. This third edition has been updated to reflect current best practices and the abundance of chan......一起来看看 《Programming Python》 这本书的介绍吧!