Python monitors whether the host is alive and sends an alarm via email. python monitors the host for alive
Python is used to write a simple script to test whether the host is alive. This script is not suitable for online use, because network delay and packet loss may cause false positives, in the future, an alert email will be sent after the ping command fails three times and multi-thread processing will be enabled.
#! /Usr/bin/env python # coding: UTF-8 import time import pexpect import smtplib from email. mime. text import MIMEText mail_host = "smtp.163.com" # define smtp server mail_to = "baojingtongzhi@163.com" # mail recipient mail_from = "monitor@163.com" # mail sender mail_pass = "123456" # mail sender mailbox password while True: def Mail (error_ip): date = time. strftime ('% Y-% m-% d % H: % M: % s') msg = MIMEText ("% S Ping % s failed from 255.252. "% (date, error_ip) msg ['subobject'] =" Ping % s failed. "% error_ip # define the mail subject msg ['from'] = mail_from msg ['to'] = mail_to try: s = smtplib. SMTP () # create an SMTP () object s. connect (mail_host, "25") # connect to the smtp host s. starttls () # Start Secure Transmission Mode s. login (mail_from, mail_pass) # email account logon authentication s. sendmail (mail_from, mail_to, msg. as_string () # mail sent by s. quit () # Disconnect the smtp connection except T Exception, e: print str (e) ip_list = ['100. 168.18.10 ', '2017. 168.18.11 ', '2017. 168.18.12 '] for ip in ip_list: ping = pexpect. spawn ('Ping-c 1% s' % ip) check = ping. secondary CT ([pexpect. TIMEOUT, "1 packets transmitted, 1 received, 0% packet loss"], 2) #2 indicates TIMEOUT if check = 0: Mail (ip) print "Ping % s failed, have email. "% ip if check = 1: print" Ping % s successful. "% ip print" Sleep 10s... "time. sleep (10) # Run it directly # python ping. py Ping 192.168.18.10 successful. ping 192.168.18.11 successful. ping 192.168.18.12 successful. sleep 10 s...
The above is all the content in this article, hoping to help you learn whether the Python monitoring host is alive and send an email alert.