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

yipeiwu_com6年前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监控主机是否存活并以邮件报警有所帮助。

相关文章

钉钉群自定义机器人消息Python封装的实例

钉钉群自定义机器人消息Python封装的实例

一、钉钉群自定义机器人介绍 钉钉群机器人是钉钉群的一个高级扩展功能,然而使用起来却非常简单,只有注册一个钉钉账号即可,就可以将第三方服务的信息聚合到钉钉群中,实现信息的自动化同步,例如:...

python应用程序在windows下不出现cmd窗口的办法

python写的GTK程序,会有这样一个怪现象,本来在cmd下用 python xxx.py 启动,还好好的,但是用py2exe编译以后,再用subprocess调用命令行程序的时候,就...

Python3将jpg转为pdf文件的方法示例

本文实例讲述了Python3将jpg转为pdf文件的方法。分享给大家供大家参考,具体如下: #coding=utf-8 #!/usr/bin/env python """ conve...

python实现查询IP地址所在地

python实现查询IP地址所在地

使方法一、用IP138数据库查询域名或IP地址对应的地理位置。 #-*- coding:gbk -*- import urllib2 import re try: while...

python tkinter控件布局项目实例

python tkinter控件布局项目实例

这篇文章主要介绍了python tkinter控件布局项目实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码部分: from...