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 70行代码实现简单算式计算器解析

描述:用户输入一系列算式字符串,程序返回计算结果。 要求:不使用eval、exec函数。 实现思路:找到当前字符串优先级最高的表达式,在算术运算中,()优先级最高,则取出算式最底层的()...

详解python中@的用法

python中@的用法 @是一个装饰器,针对函数,起调用传参的作用。 有修饰和被修饰的区别,‘@function'作为一个装饰器,用来修饰紧跟着的函数(可以是另一个装饰器,也可以是函数...

pycharm 将python文件打包为exe格式的方法

pycharm 将python文件打包为exe格式的方法

因为近期正在学习python,就需要将python文件打包为exe可执行文件,就将该过程记录下来。 首先我是通过Pyinstall打包的,具体安装及打包步骤如下 1.打开终端控制台 通过...

python pyinstaller打包exe报错的解决方法

python pyinstaller打包exe报错的解决方法

今天用python 使用pyinstaller打包exe出现错误 环境pyqt5 + python3.6 32位 在导入pyqt5包之前加上如下代码 import sys impo...

python连接池实现示例程序

复制代码 代码如下:import socketimport Queueimport threading def worker():    while Tru...