python监控主机是否存活并以邮件报警

利用python写了简单测试主机是否存活脚本,此脚本不适于线上使用,因为网络延迟、丢包现象会造成误报邮件,那么后续会更新判断三次ping不通后再发报警邮件,并启用多线程处理。

#!/usr/bin/env python
# coding:utf-8
import time
import pexpect
import smtplib
from email.mime.text import mimetext
mail_host = “smtp.163.com” #定义smtp服务器
mail_to = “baojingtongzhi@163.com” #邮件收件人
mail_from = “monitor@163.com” #邮件发件人
mail_pass = “123456” #邮件发件人邮箱密码
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[‘subject’] = “ping %s failed.” % error_ip #定义邮件主题
msg[‘from’] = mail_from
msg[‘to’] = mail_to
try:
s = smtplib.smtp() #创建一个smtp()对象
s.connect(mail_host, “25”) #通过connect方法连接smtp主机
s.starttls() #启动安全传输模式
s.login(mail_from,mail_pass) #邮箱账户登录认证
s.sendmail(mail_from, mail_to, msg.as_string()) #邮件发送
s.quit() #断开smtp连接
except exception, e:
print str(e)
ip_list = [‘192.168.18.10’,
‘192.168.18.11’,
‘192.168.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 “ping %s failed,have email.” % ip
if check == 1:
print “ping %s successful.” % ip
print “sleep 10s…”
time.sleep(10)
#直接运行
# python ping.py
ping 192.168.18.10 successful.
ping 192.168.18.11 successful.
ping 192.168.18.12 successful.
sleep 10s…

以上就是本文的全部内容,希望对大家学习python监控主机是否存活并以邮件报警有所帮助。

Posted in 未分类

发表评论