如何利用python监控主机存活并邮件、短信通知?

  • 功能:

1、使用定时任务执行脚本,检查主机存活信息

2、将主机存活信息写入指定文件

3、发现宕机的主机后给用户发邮件提醒

备注:因为139邮箱在接受到邮件后会自动给用户发送条短信告知(且此服务免费),所以间接的实现了短信提醒功能。

  • 代码如下:
# -*- coding: utf-8 -*-
import os
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header


# 第三方 SMTP 服务
mail_host = "***"  #设置服务器
mail_user="***@***.***"    #用户名
mail_pass="****"   #口令

sender = "****" #发件人信息
receivers = ['****']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱



hostname = [] #在列表中填写需要检测的主机地址或域名
f=open('d:/ping.txt','a+')
f.write("-----------------"+"检查开始时间为:"+time.strftime('%Y-%m-%d %H:%M:%S')+"------------------"+"\n")
f.close()
for ip in hostname:
    response = os.system("ping -n 4 " + ip)
    if response == 0:
        data = ip + " " + 'is up!' + " " +  time.strftime('%Y-%m-%d %H:%M:%S')
        print data
        f=open('d:/ping.txt','a+')
        f.write(data + '\n')
        f.close()     
    else:
        data = ip + " " + 'is down!' + " " + time.strftime('%Y-%m-%d %H:%M:%S')
        print data
        f=open('d:/ping.txt','a+')
        f.write(data + '\n')
        f.close()
        message = MIMEText(data, 'plain', 'utf-8')
        message['From'] = Header("告警中心", 'utf-8')
        message['To'] =  Header("flanker", 'utf-8')

        subject = '【注意】有设备宕机'
        message['Subject'] = Header(subject, 'utf-8')


        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(mail_host,25)    # 25 为 SMTP 端口号
            #smtpObj.starttls()
            smtpObj.login(mail_user,mail_pass) 
            smtpObj.sendmail(sender, receivers, message.as_string())
            print "邮件发送成功"
        except smtplib.SMTPException:
            print "Error: 无法发送邮件"
      
f=open('d:/ping.txt','a+')
f.write("-----------------"+"检查结束时间为:"+time.strftime('%Y-%m-%d %H:%M:%S')+"------------------"+"\n"+"\n")
f.close()