利用Python自动监控网站并发送邮件告警的方法


Posted in Python onAugust 24, 2016

前言

因为有一些网站需要每日检查是否有问题,所以需要一个报警监控的机制,这个需要你指定你发送的邮箱和你接收的邮箱,就可以做到对网站自动监控了。

这里用的是python3.5

需要安装的插件:

      1、smtplib:发邮件需要用到

      2、pycurl:访问网站时会需要用到

      3、linecache:在读取txt网站清单时需要用到

具体思路:

python程序从txt里面批量读取到网站的信息,通过Curl.py模拟浏览器去访问网站,并且把访问的结果写入到以自己的网站名称-日期.txt格式的文件中记录;有几种情况:

1、如果发现打不开了,直接发邮件提示网站已经打不开

2、发现可以打开,读取文件中上一次访问的情况(读取txt文件最后一行),

    1)如果发现上一次是打不开的,发邮件提醒网站已经恢复了

    2)如果发现上一次是打得开的(200的返回码),只是记录网站访问的日志就可以了

总共4个文件

Email.py是邮件类,主要用来发邮件的时候调用,这里需要按照你的情况改成你的邮箱(msg['From']),邮箱服务器地址(SMTP地址),和你的邮箱密码(SMTP.login)

Email.py

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class Email_send(object):
 def __init__(self,msgTo,data2,Subject):
  self.msgTo=msgTo
  self.data2=data2
  self.Subject=Subject
 def sendEmail(self):
  # (attachment,html) = content
  msg = MIMEMultipart()
  msg['Subject'] = self.Subject
  msg['From'] = 'xxxx@xxxx.com.cn'
  msg['To'] = self.msgTo
  html_att = MIMEText(self.data2, 'html', 'utf-8')
  #att = MIMEText(attachment, 'plain', 'utf-8')
  msg.attach(html_att)
  #msg.attach(att)
  try:
   smtp = smtplib.SMTP()
   smtp.connect('smtp.xxxx.com', 25)
   smtp.login(msg['From'], 'xxxx') #改成自己的邮箱密码
   smtp.sendmail(msg['From'], msg['To'].split(','), msg.as_string())
   return('邮件发送成功')
  except Exception as e:
   print('--------------sss------',e)
 def curl(self):
  import pycurl
  c=pycurl.Curl()
  #url="www.luoan.com.cn"
  #indexfile=open(os.path.dirname(os.path.realpath(__file__))+"/content.txt","wb")
  c.setopt(c.URL,url)
  c.setopt(c.VERBOSE,1)
  c.setopt(c.ENCODING,"gzip")
  #模拟火狐浏览器
  c.setopt(c.USERAGENT,"Mozilla/5.0 (Windows NT 6.1; rv:35.0) Gecko/20100101 Firefox/35.0")
  return c

Curl.py 主要用来执行模拟浏览器访问网站并返回结果的文件

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import pycurl
class Curl(object):
 def __init__(self,url):
  self.url=url
 def Curl_site(self):
  c=pycurl.Curl()
  #url="www.luoan.com.cn"
  #indexfile=open(os.path.dirname(os.path.realpath(__file__))+"/content.txt","wb")
  c.setopt(c.URL,self.url)
  c.setopt(c.VERBOSE,1)
  c.setopt(c.ENCODING,"gzip")
  #模拟火狐浏览器
  c.setopt(c.USERAGENT,"Mozilla/5.0 (Windows NT 6.1; rv:35.0) Gecko/20100101 Firefox/35.0")
  return c

site_moniter.py 这个文件为主程序,主要执行调用上面的函数,读取txt文件中的网站清单,如果网站打不开就发邮件出来告警

需要注意:

      1、把xxxx@xxxx.com改成你自己的邮箱,

      2、把文件路径改成自己的真实路径

#!/usr/bin/python
#-*- coding:utf-8 -*-
import pycurl
import os
import sys
import linecache
import time #引入事件类,用来获取系统当前时间
#from ceshi import Student
from Email import Email_send
from Curl import Curl

#bart = Student('mafei',59)
#bart.print_score()

def script(urls,type):
 msgTo = 'xxxx@xxxx.com'
 now_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
 j=1
#  data2=[{'aa':'aa'}]
 for url_split in urls:
  #print(url_split)
  url_1=url_split.split('---')
  url=url_1[1]
  recovery_title = "监控通知----%s url:%s" % (url_1[0], url) + "在" + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) + "已经恢复"
  down_title = "监控通知----%s url:%s" % (url_1[0], url) + "在" + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) + "无法打开"
  #print('~~~~~~~~~~~~~~~~~~~')
  #print(url)
  #引用爬去网站的类,调用结果
  url_result = Curl(url)
  c = url_result.Curl_site()
  try:
   c.perform()
   code = str(c.getinfo(c.HTTP_CODE))
   print(code+'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
  except Exception as e:
   print('--------错误信息:--------',e)
   #indexfile.close()
   #c.close()
  code = str(c.getinfo(c.HTTP_CODE))
  # print(code+'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
  filename = '%s-%s.txt' % (url_1[0], time.strftime("%Y-%m-%d", time.localtime(time.time())))
  #判断如果在网站无法打开的情况下
  if code == '0' or code=='400' or code=='500' or code=='404':
   resolveTime = 0
   Connection_Time = 0
   Transfer_Total_Time = 0
   Total_Time = 0
   # print('为000000000000000000000000000000000000000000')
   data3 = '网站:%s无法打开%s' % (url_1[0], url)
   # indexfile.close()
   # c.close()
   #判断网站如果挂了就发邮件
   stat3 = Email_send(msgTo, data3, down_title)
   resole=stat3.sendEmail()
   print(resole)
   print(data3 + '邮件已经发送')
  else:
   #resolveTime = str(c.getinfo(c.NAMELOOKUP_TIME) * 1000) + " ms"
   # Connection_Time=str(float(c.getinfo(c.CONNECT_TIME)*1000-c.getinfo(c.NAMELOOKUP_TIME)*1000))+" ms"
   #Connection_Time = str(c.getinfo(c.CONNECT_TIME) * 1000 - c.getinfo(c.NAMELOOKUP_TIME) * 1000) + " ms"
   # Connection_Time=round(float(Connection_Time))
   #Transfer_Total_Time = str(c.getinfo(c.TOTAL_TIME) * 1000 - c.getinfo(c.PRETRANSFER_TIME) * 1000) + " ms"
   #Total_Time = str(c.getinfo(c.TOTAL_TIME) * 1000) + " ms"
   # data2=data
   # data={'url':url,'HTTP CODE':code,'resolveTime':resolveTime,'Connection_Time':Connection_Time,'Transfer_Total_Time':Transfer_Total_Time,'Total_Time':Total_Time}
   print('网站可以正常打开')
   #f = open(filename, 'a',encoding='utf-8')
   file_exit=os.path.exists(filename)
   #print(file_exit)
   #判断这个日志文件存不存在
   if(file_exit):
    #读取文件最后一行,为了读取出来最后一次的状态值
    file = open(filename, 'r',encoding='utf-8')
    linecount = len(file.readlines())
    data = linecache.getline(filename, linecount)
    file.close
    if data == '':
     print('这是'+data+'为空的数据')
    else:
     print('其他信息%s'%(data))
     explode = data.split('----')
     #判断如果读取出来的值,最后一次是异常的情况就告警
     if explode[3]=='0\n' or explode[3]=='400\n' or explode[3]=='500' or explode[3]=='404':
      data3 = '网站:%s在%s已经恢复%s' % (url_1[0], now_time,url)
      stat3 = Email_send(msgTo, data3, recovery_title)
      resole = stat3.sendEmail()
      print(resole)
      print(data3 + '邮件已经发送')
     else:
      print('最后一次记录为其他值:%s'%(explode[3])+'-----')
   else:
    print('文件不存在')
  data2 = '\n' + url_1[0] + '----' + url + '-----' + time.strftime("%H:%M:%S", time.localtime(time.time())) + '-------' + code
  print('data2数据写入成功:' + data2)
  file = open(filename, 'a', encoding='utf-8')
  file.write(data2)
  file.close
# bart = Student(data2,59)
# bart.print_score()

if __name__ == "__main__":
 type = "监控通知-测试" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
 data1=['公司门户---www.luoan.com.cn','公司平台---yun.luoan.com.cn']
 #script(data1,type)


 #中心层面的网站清单
 file=open('D:\python\site_moniter\zhongxin.txt')
 data2=[]
 while 1:
  line2 =file.readline()
  print(line2)
  if not line2:
   break
  data2.append(line2[0:-1])
 #data2=['www.luoan.com.cn','yun.luoan.com.cn','www.qq.com']
 print(data2)
 title="监控通知-中心"+ time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
 script(data2,title)

总结

利用Python自动监控网站并发送邮件告警的方法到这就基本结束了,希望对大家的学习工作能有所帮助。

Python 相关文章推荐
selenium python浏览器多窗口处理代码示例
Jan 15 Python
python字符串string的内置方法实例详解
May 14 Python
python禁用键鼠与提权代码实例
Aug 16 Python
分享PyCharm的几个使用技巧
Nov 10 Python
Python内置加密模块用法解析
Nov 25 Python
实例代码讲解Python 线程池
Aug 24 Python
Windows下pycharm安装第三方库失败(通用解决方案)
Sep 17 Python
基于Python爬取京东双十一商品价格曲线
Oct 23 Python
python中Mako库实例用法
Dec 31 Python
发工资啦!教你用Python实现邮箱自动群发工资条
May 10 Python
一劳永逸彻底解决pip install慢的办法
May 24 Python
Python如何使用循环结构和分支结构
Apr 13 Python
巧用python和libnmapd,提取Nmap扫描结果
Aug 23 #Python
Python中属性和描述符的正确使用
Aug 23 #Python
Python实现基本线性数据结构
Aug 22 #Python
Python进行数据提取的方法总结
Aug 22 #Python
详解Python实现按任意键继续/退出的功能
Aug 19 #Python
利用Python开发微信支付的注意事项
Aug 19 #Python
Python用模块pytz来转换时区
Aug 19 #Python
You might like
PHP的伪随机数与真随机数详解
2015/05/27 PHP
php pdo oracle中文乱码的快速解决方法
2016/05/16 PHP
JavaScript中的面向对象介绍
2012/06/30 Javascript
js父页面与子页面不同时显示的方法
2014/10/16 Javascript
js中的json对象详细介绍
2014/10/29 Javascript
Nodejs学习笔记之Stream模块
2015/01/13 NodeJs
基于js实现微信发送好友如何分享到朋友圈、微博
2015/11/30 Javascript
JS日程管理插件FullCalendar简单实例
2017/02/07 Javascript
angular ng-click防止重复提交实例
2017/06/16 Javascript
js图片轮播插件的封装
2017/07/21 Javascript
基于ES6 Array.of的用法(实例讲解)
2017/09/05 Javascript
vue 实现全选全不选的示例代码
2018/03/29 Javascript
微信小程序框架wepy之动态控制类名
2018/09/14 Javascript
vue 指令之气泡提示效果的实现代码
2018/10/18 Javascript
小程序测试后台服务的方法(ngrok)
2019/03/08 Javascript
[58:23]LGD vs TNC 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/16 DOTA
Python 学习笔记
2008/12/27 Python
python处理cookie详解
2014/02/07 Python
Python实现模拟时钟代码推荐
2015/11/08 Python
Python黑魔法Descriptor描述符的实例解析
2016/06/02 Python
Python编程之string相关操作实例详解
2017/07/22 Python
python和ruby,我选谁?
2017/09/13 Python
Python多重继承的方法解析执行顺序实例分析
2018/05/26 Python
浅谈Python 列表字典赋值的陷阱
2019/01/20 Python
Python正则表达式匹配和提取IP地址
2019/06/06 Python
python GUI库图形界面开发之PyQt5中QWebEngineView内嵌网页与Python的数据交互传参详细方法实例
2020/02/26 Python
CSS3实例分享--超炫checkbox复选框和radio单选框
2014/09/01 HTML / CSS
HTML5 progress和meter控件_动力节点Java学院整理
2017/07/06 HTML / CSS
美国领先的家庭健康检测试剂盒提供商:LetsGetChecked
2019/03/18 全球购物
我能否用void** 指针作为参数, 使函数按引用接受一般指针
2013/02/16 面试题
计算机专业自我鉴定
2013/10/15 职场文书
迟到检讨书大全
2014/01/25 职场文书
劲霸男装广告词改编版
2014/03/21 职场文书
大学生村官个人总结
2015/02/15 职场文书
python人工智能human learn绘图可创建机器学习模型
2021/11/23 Python
Python中的嵌套循环详情
2022/03/23 Python