python监控服务器信息,Python监控服务器实现邮件微信报警
本文中筆者暫時實現的只有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监控服务器信息,Python监控服务器实现邮件微信报警的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 给爹妈换路由如何给家里换路由器
- 下一篇: 循环发ajax请求,在循环中发送jque