搜尋
首頁後端開發Python教學Python自動監控網站並發送郵件告警

前言

因為有一些網站需要每日檢查是否有問題,所以需要一個警報監控的機制,這個需要你指定你發送的郵箱和你接收的信箱,就可以做到對網站自動監控了。

這裡用的是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自動監控網站並發送郵件警報相關文章請關注PHP中文網!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

舉一個場景的示例,其中使用Python列表比使用數組更合適。舉一個場景的示例,其中使用Python列表比使用數組更合適。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python數組中訪問元素?您如何在Python數組中訪問元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Apr 28, 2025 pm 04:34 PM

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

Python中的模塊和包裝是什麼?Python中的模塊和包裝是什麼?Apr 28, 2025 pm 04:33 PM

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

Python中的Docstring是什麼?Python中的Docstring是什麼?Apr 28, 2025 pm 04:30 PM

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具