The use of Python to write a simple test host survival script, this script is not suitable for online use, because the network delay, packet loss caused by false positive mail, then the subsequent update to determine the three ping not pass the alarm message, and enable multi-threaded processing.
#!/usr/bin/env Python # coding:utf-8 import time import pexpect import smtplib from email.mime.text import Mimetext mail_h ost = "smtp.163.com" #定义smtp服务器 mail_to = "baojingtongzhi@163.com" #邮件收件人 mail_from = "monitor@163.com" #邮件发件人 mail_p "123456" #邮件发件人邮箱密码 while True:def Mail (error_ip): date = Time.strftime ('%y-%m-%d%h:%m:%s ') msg = m Imetext ("%s ping%s failed from 255.252."% (date, error_ip)) msg[' Subject '] = "ping%s failed."% error_ip #定义邮件主题 Msg["from" = Mail_from msg[' to '] = mail_to try:s = smtplib. SMTP () #创建一个SMTP () object S.connect (Mail_host, "") #通过connect方法连接smtp主机 S.starttls () #启动安全传输 Mode S.login (Mail_from,mail_pass) #邮箱账户登录认证 s.sendmail (Mail_from, Mail_to, msg.as_string ()) #邮件发送 S.qu It () #断开smtp连接 except Exception, E:print str (e) ip_list = [' 192.168.18.10 ', ' 192.168.18.11 ', ' 192.1 68.18.12 '] for IP in ip_list:ping = Pexpect.spawn (' Ping-c 1%s '% IP) check = Ping.expect ([Pexpect. TIMEOUT, "1 packets transmitted, 1 received, 0% packet loss"],2) #2代表超时时间 if check = = 0:mail (IP) print "P ing%s failed,have email. "% IP If check = = 1:print" Ping%s successful. "% IP print" Sleep 10s ... "Time.sle EP (Ten) #直接运行 # python ping.py Ping 192.168.18.10 successful. Ping 192.168.18.11 successful. Ping 192.168.18.12 successful. Sleep 10s ...
The above is the entire content of this article, I hope that you learn Python monitoring host whether to survive and to mail alarm help.