This article mainly introduces how to monitor the abnormal running of a python website and send emails. it involves Python mail operation and server monitoring techniques and has some reference value, for more information about how to monitor exceptions on a python website and send emails, see the following example. Share it with you for your reference. The details are as follows:
This is a simple monitoring program developed in python. when the specified webpage status is abnormal, a notification email is sent through smtp.
The code is as follows:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# Author libertyspy
Import socket
Import smtplib
Import urllib
Mail_options = {
'Server': 'smtp .qq.com ', # The smtp service of QQ is used. you need to enable the SMTP service in your mailbox.
'Port': 25, # port
'User': 'hacker @ qq.com ', # sender
'Pwd': 'hacker', # sender's password
'Send _ to': 'Sniper @ qq.com ', # recipient
}
Msg_options = {
'User': 'hacker', # user name of the SMS platform
'Pwd': '000000', # SMS platform password
'Phone': '000000', # The phone number to send a text message
}
Test_host = 'http: // www.lastme.com /'
Def url_request (host, port = 80 ):
Try:
Response = urllib. urlopen (host)
Response_code = response. getcode ()
If 200! = Response_code:
Return response_code
Else:
Return True
Handle T IOError, e:
Return False
Def send_message (msg, host, status ):
Send_msg = 'server: % s hung! Status Code: % s' % (host, status)
Request_api = "http://www.uoleem.com.cn/api/uoleemApi? Username = % s & pwd = % s & mobile = % s & content = % s "\
% (Msg ['user'], msg ['pwd'], msg ['phone'], send_msg)
Return url_request (request_api)
Def send_email (mail, host, status ):
Smtp = smtplib. SMTP ()
Smtp. connect (mail ['server'], mail ['port'])
Smtp. login (mail ['user'], mail ['pwd'])
Msg = "From: % s \ rTo: % s \ rSubject: Server: % s hung! Status Code: % s \ r \ n "\
% (Mail ['user'], mail ['send _ to'], host, status)
Smtp. sendmail (mail ['user'], mail ['send _ to'], msg)
Smtp. quit ()
"""
Def check_status (host, port = 80 ):
S = socket. socket ()
Ret_msg = []
Try:
S. connect (host, port ))
Return True
Failed T socket. error, e:
Return False
"""
If _ name __= = '_ main __':
Status = url_request (test_host)
If status is not True and status is not None:
Send_email (mail_options, test_host, status)
Send_message (msg_options, test_host, status)
Else:
Pass
I hope this article will help you with Python programming.