利用python3监控服务器状态进行邮件报警

  在正式的生产环境中,我们常常会需要监控服务器的状态,以保证公司整个业务的正常运转,常常我们会用到像nagios、zabbix这类工具进行实时监控,那么用python我们怎么进行监控呢?这里我们利用了python3调用psutil和yagmail这两个模块进行监测服务器的内存、磁盘、cpu状态(以及我们监控apache运行状态用到的socket模块)

监控内存、磁盘、cpu

import psutil

def mem():

mem = psutil.virtual_memory()

return mem[2]

def disk():

disk = psutil.disk_usage('/root')

return disk[3]

def cpu():

cpu = psutil.cpu_percent(60)

return cpu

a = mem()

b = disk()

c = cpu()

import yagmail

yag = yagmail.SMTP(user='[email protected]', password='cxboscylplifgadd', host='smtp.qq.com')

if a > 80:

yag.send(to='[email protected]',subject='内存报警',contents='运行内存超过80%请尽快处理',cc='[email protected]')

yag.close()

if b > 70:

yag.send(to='[email protected]',subject='系统磁盘报警', contents='系统磁盘超过70%请尽快处理',cc='[email protected]')

yag.close()

if c > 90:

yag.send(to='[email protected]',subject='cpu报警', contents='cpu超过90%请尽快处理',cc='[email protected]')

yag.close()

监控网页服务(报警)

import socket,yagmail

hosts = ['192.168.8.137:80','192.168.8.15:88']

socket.setdefaulttimeout(5)

for host in hosts:

ip = host.split(':')[0]

port = host.split(':')[1]

server = socket.socket()

res =server.connect_ex((ip,int(port)))#返回值为0代表ok,不为0代表失败

if res == 0:

pass

else:

yag = yagmail.SMTP(user='[email protected]', password='cxboscylplifgadd', host='smtp.qq.com')

yag.send(to='[email protected]', subject='警告', contents='%s httpd服务断开请检测' % ip, cc='[email protected]')

yag.close()

  这样我们的监控脚本python脚本就完成了,现在就只需要拿到服务器执行定时任务就行了。现在我们来检测一下:

 编辑一下定时任务

 我们将写上面两个脚本写入1.py和2.py这两个文件中,为了方便验证我们将磁盘判断值改为30,实际上我们已用到了40%,这样就能直接报警了,两台服务器的Apache端口都为80且均为正常运行状态。

 我们等待一分钟。。。。。。。

 

 我们收到两封报警邮件,是不是很方便呢?

猜你喜欢

转载自www.cnblogs.com/lxwei0101/p/11701299.html