찾다
백엔드 개발파이썬 튜토리얼Python으로 웹사이트 일괄 모니터링을 구현하는 방법에 대한 자세한 설명과 예시

이 기사에서는 여러 웹사이트의 가용성 모니터링을 구현하는 매우 실용적인 Python 스크립트를 핵심 사항에 대한 설명과 함께 공유합니다. 동일한 요구 사항을 가진 친구들이 참고할 수 있습니다

">

최근에는 사이트가 늘어나면서 관리의 복잡성도 높아졌습니다. 너무 많은 사람을 관리하기가 어렵다는 것을 알게 되었습니다. 물론 중요한 사이트와 중요하지 않은 사이트도 더 많이 관리됩니다. 예를 들어 1만년 동안 문제가 없었던 사이트도 점차 잊혀지고 있습니다. 어느 날 갑자기 문제가 발생하면 여전히 응급 치료가 필요하므로 오늘은 규모가 크던 작던 사이트에 관계없이 첫 번째 조치를 취하는 것이 필요합니다. , 먼저 통합 모니터링을 구현해야 합니다. 적어도 해당 사이트에 접속할 수 없다는 점은 최대한 빨리 보고해 주시기 바랍니다. 그러면 Python을 사용하여 여러 웹사이트의 가용성 모니터링을 구현하는 방법을 살펴보겠습니다.

#!/usr/bin/env python
 
 
import pickle, os, sys, logging
from httplib import HTTPConnection, socket
from smtplib import SMTP
 
def email_alert(message, status):
  fromaddr = 'xxx@163.com'
  toaddrs = 'xxxx@qq.com'
  
  server = SMTP('smtp.163.com:25')
  server.starttls()
  server.login('xxxxx', 'xxxx')
  server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
  server.quit()
 
def get_site_status(url):
  response = get_response(url)
  try:
    if getattr(response, 'status') == 200:
      return 'up'
  except AttributeError:
    pass
  return 'down'
    
def get_response(url):
  try:
    conn = HTTPConnection(url)
    conn.request('HEAD', '/')
    return conn.getresponse()
  except socket.error:
    return None
  except:
    logging.error('Bad URL:', url)
    exit(1)
    
def get_headers(url):
  response = get_response(url)
  try:
    return getattr(response, 'getheaders')()
  except AttributeError:
    return 'Headers unavailable'
 
def compare_site_status(prev_results):
  
  def is_status_changed(url):
    status = get_site_status(url)
    friendly_status = '%s is %s' % (url, status)
    print friendly_status
    if urlin prev_resultsand prev_results[url] != status:
      logging.warning(status)
      email_alert(str(get_headers(url)), friendly_status)
    prev_results[url] = status
 
  return is_status_changed
 
def is_internet_reachable():
  if get_site_status('www.baidu.com') == 'down' and get_site_status('www.sohu.com') == 'down':
    return False
  return True
  
def load_old_results(file_path):
  pickledata = {}
  if os.path.isfile(file_path):
    picklefile = open(file_path, 'rb')
    pickledata = pickle.load(picklefile)
    picklefile.close()
  return pickledata
  
def store_results(file_path, data):
  output = open(file_path, 'wb')
  pickle.dump(data, output)
  output.close()
  
def main(urls):
  logging.basicConfig(level=logging.WARNING, filename='checksites.log', 
      format='%(asctime)s %(levelname)s: %(message)s', 
      datefmt='%Y-%m-%d %H:%M:%S')
  
  pickle_file = 'data.pkl'
  pickledata = load_old_results(pickle_file)
  print pickledata
    
  if is_internet_reachable():
    status_checker = compare_site_status(pickledata)
    map(status_checker, urls)
  else:
    logging.error('Either the world ended or we are not connected to the net.')
    
  store_results(pickle_file, pickledata)
 
if __name__ == '__main__':
  main(sys.argv[1:])

스크립트 핵심 설명:

1. getattr()은 Python의 내장 함수입니다. 객체 속성에 따라 객체의 값을 반환할 수 있습니다.

2. 내부적으로 정의된 함수입니다.

3. map()에는 두 개의 매개변수가 필요합니다. 하나는 함수이고 다른 하나는 시퀀스의 각 요소에 함수 메서드를 적용하는 것입니다.

위 내용은 Python으로 웹사이트 일괄 모니터링을 구현하는 방법에 대한 자세한 설명과 예시의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?May 03, 2025 am 12:11 AM

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.May 03, 2025 am 12:10 AM

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?May 03, 2025 am 12:06 AM

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?May 03, 2025 am 12:03 AM

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.May 03, 2025 am 12:01 AM

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

파이썬 목록을 어떻게 슬라이스합니까?파이썬 목록을 어떻게 슬라이스합니까?May 02, 2025 am 12:14 AM

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?May 02, 2025 am 12:09 AM

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?May 02, 2025 am 12:09 AM

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구