Python3 monitor server status using the mail alarm

  In the formal production environment, we often need to monitor the state of the server, to ensure the normal operation of the company's entire business, often we will use as nagios, zabbix this type of real-time monitoring tool, then use python how we monitor it? Here we use python3 call psutil and yagmail two modules to monitor the server's memory, disk, cpu state (and we monitor apache running state used socket module)

Monitor memory, disk, 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 'memory alarm' , Contents = 'Please run over 80% of memory as soon as possible' , CC = '[email protected]' )

yag.close()

if b > 70:

yag.send (to = '[email protected]' , Subject = 'alarm system disk' , Contents = 'disk system make more than 70% as soon as possible' , CC = '[email protected]' )

yag.close()

if c > 90:

yag.send (to = '[email protected]' , Subject = 'CPU alarm' , Contents = 'Please than 90% CPU as soon as possible' , CC = '[email protected]' )

yag.close()

Monitoring Web Services (alarm)

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()

server.connect_ex = RES ((IP, int (Port))) # returns a value of 0 representative of ok, not 0 for failure

if res == 0:

pass

else:

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

yag.send (to = '[email protected]' , Subject = 'warning' , Contents = '% S detecting the httpd service disconnect request' % IP, CC = '[email protected]' )

yag.close()

  So that our monitoring scripts python script is complete, and now you only need to get the server to perform regular tasks on the line. Now we have to detect it:

 

 Edit about regular tasks

 

 We will write two scripts written 1.py above and 2.py these two documents, in order to facilitate the validation of our value to determine the disk 30, in fact, we have used the 40 percent, so you can directly call the police, two Apache server port 80 and are the normal operating state.

 

 We wait a minute. . . . . . .

 

 

 

 We received two warning messages, it is not very convenient?

Guess you like

Origin www.cnblogs.com/lxwei0101/p/11701299.html