Python's way of monitoring a website for exceptions and sending an email

  • 2020-04-02 14:38:46
  • OfStack

This example shows how python monitors web site exceptions and sends mail. Share with you for your reference. The details are as follows:

This is a simple python development monitor that sends notification emails via SMTP when a specified web page is in abnormal state

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#author  libertyspy
import socket
import smtplib
import urllib
mail_options = {
    'server':'smtp.qq.com',# Using the QQ the SMTP Service, which needs to be opened in the mailbox SMTP service
    'port':25,             # port
    'user':'hacker@qq.com',# The sender
    'pwd':'hacker',        # The sender's password
    'send_to':'sniper@qq.com',  # recipient
}
msg_options={
    'user':'hacker',    # The user name of the SMS platform
    'pwd':'74110',      # SMS platform password
    'phone':'12345678910',   # The phone number you need to text
}
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
    except IOError,e:
        return False
def send_message(msg,host,status):
    send_msg=' The server :%s Hang up! 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:%srTo:%srSubject: The server : %s Hung up the ! Status code :%srn"
         % (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
    except 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 has helped you with your Python programming.


Related articles: