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设定并获取socket超时时间的方法

python写法 import socket def test_socket_timeout(): s = socket.socket(socket.AF_INET,...

Python3下错误AttributeError: ‘dict’ object has no attribute’iteritems‘的分析与解决

引言 目前Python2和Python3存在版本上的不兼容性,这里将列举dict中的问题之一。下面话不多说,来看看详细的介绍: 1. Python 2  vs python 3...

基于Python Shell获取hostname和fqdn释疑

一直以来被Linux的hostname和fqdn(Fully Qualified Domain Name)困惑了好久,今天专门抽时间把它们的使用细节弄清了。 一、设置hostname/...

python自动化测试之从命令行运行测试用例with verbosity

python自动化测试之从命令行运行测试用例with verbosity

本文实例讲述了python自动化测试之从命令行运行测试用例with verbosity,分享给大家供大家参考。具体如下: 实例文件recipe3.py如下: class RomanN...

Python 解码Base64 得到码流格式文本实例

我就废话不多说了,直接上代码吧! # coding:utf8 import base64 def BaseToFlow(): while True: str =...