Python3 enables simple ping monitoring and launches alarm messages
1, the implementation of the principle of the result of the ping command to get the packet loss rate and delay, when the packet loss rate and delay reached the preset value, the result as the message content, and send mail
2, The mail is sent with smtplib and email implementation
3, the current script has a small problem is: I open the file, loop read, when the first line, I do ping, get the results, write the results into a file, and determine whether to reach the default value, if reached, the results added to the message content, so always loop, when the file read, and then close the two files, Send the message again. Always learn a bit of a problem, you should save the results to a list, write Once. Forget it, play it like this First.
The code is as Follows:
# -*- coding:utf-8 -*-__author__ = ' Guozhaohui ' __version__ = ' 0.0.3 ' __datetime__ = ' 2016-12-30 03:30:00 ' Import osimport subprocessimport smtplibimport sysfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import mimebasefrom email.mime.text import mimetextfrom email.utils import commaspace,formatdatefrom email import encoders# server[' Name '], server[' user '], server[' passwd ']def send_mail (server, fro, to, subject= "", text= "", files=[]): assert type (server) == dict assert type (to) == list assert type (files) == list msg = mimemultipart () msg[' from '] = fro # the sender of the message msg[' Subject '] = subject # subject of mail msg[' to '] = commaspace.join # commaspace== ', ' recipients can be multiple, to is a list msg[' Date '] = formatdate (localtime=true) # send Time Msg.attach (mimetext (text, ' plain ', ' utf-8 ')) for file in files: # Add attachments can be multiple, files is a list, can be empty part = mimebase (' application ', ' octet-stream ') # ' Octet-stream ': binary data with open (file, ' RB ') as f : part.set_payload (f.read ()) &nBsp; encoders.encode_base64 (part) part.add_header (' Content-disposition ', ' attachment; filename= "%s" ' % os.path.basename (file) msg.attach (part) smtp = smtplib. SMTP () smtp.connect (server[' name ') # connect has two parameters, the first is the mail server, the second is the port, and the default is 25 smtp.login (server[' user '], server[' passwd ') # username, password smtp.sendmail (fro, to, msg.as_string ()) # sender, recipient, Send Message Smtp.close () # Close connection def ping_test (src,dest): ping = Subprocess. Popen ('/bin/ping -i 0.2 -c 4 -q -i ' + src + ' ' + dest, shell=true, stderr=subprocess. pipe, stdout=subprocess. PIPE) # Execute command res,err = ping.communicate () if err: sys.exit (err.decode (). strip (' \ n ')) pres = list (res.decode (). Split (' \ n ')) loss = pres[3].split () [5] # get packet loss rate try: rtt = pres[4].split ('/') [4] # Get Rtt avg value except IndexError: rtt = "" return loss,rttdef ping_res (file,revfile): with Open (file, ' r ', encoding= ' Utf-8 ') as f: With open (revfile, ' W ', encoding= ' utf-8 ') as f1: textmail = text = '%-15s %-15s %-15s %- 5s %-5s \n ' % (' host ', ' src ', ' dest ', ' loss ', ' RTT ') f1.write (text) for line in f: host = line.split () [0] src = line.split () [1] &nbSp; dest = line.split () [2] try: threshold = Line.split () [3] except IndexError: # default delay alarm threshold threshold = 100 loss, rtt = ping_test ( Src, dest) text = '%-15s %-15s %-15s %-5s %-5s \n ' % (host, src, dest, loss, rtt) &NBsp; f1.write (text) # Determine if the packet loss rate and delay are up to the preset value if float (loss.strip ('% ')) > 10 or float (rtt) > float (threshold) : textmail += text return textmailif __name__ == ' __main__ ': try: file = '/root/ping_test/ping_test.cfg ' # config file, format (space separated): hostname, source address, destination address, time delay threshold (default Is) revfile = '/root/ping_test/ping_test.rev ' # results file tExtmail = ping_res (file,revfile) # Mail content # print (textmail) server = {' name ': ' Mail.netpas.co ', ' user ': ' Guozhaohui ', ' passwd ': '} fro = ' [email protected] ' to = [' [email protected] '] subject = ' ping_test ' if len (textmail.split (' \ n ')) == 2 : sys.exit () # When only one line exits the program does not send mail send_mail (server,fro,to,subject,textmail) except smtPlib. Smtpauthenticationerror: sys.exit ("Mail Authentication failed ") except KeyboardInterrupt: sys.exit (249) except Exception as e: sys.exit (e)
GitHub Address: https://github.com/babyshen/Python/blob/master/monitor.py
This article is from the "baby god" blog, make sure to keep this source http://babyshen.blog.51cto.com/8405584/1887791
Python3 enables simple ping monitoring and sending alarm messages