Python监控网站异常并发送邮件通知的实现方案

沿途有光
沿途有光
发布时间:2026-10-12| 3人浏览过
原创

本文介绍使用Python编写简易网站监控程序的方法。通过urllib模块请求指定网页,检测HTTP状态码或连接错误。若发现异常,程序利用smtplib通过QQ SMTP服务发送报警邮件,并调用短信接口发送通知。代码包含完整的配置参数及主逻辑判断,适用于基础的服务状态监控场景。

本文详细讲解如何利用Python监控网站运行状态,并在检测到异常时自动发送电子邮件通知。该方案供广大开发者参考使用。

这是一个基于Python开发的简易监控脚本,主要功能是在指定网页出现访问异常时,通过SMTP协议发送通知邮件。

复制代码 代码如下:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#author libertyspy
import socket
import smtplib
import urllib
mail_options = {
    'server':'smtp.qq.com',#使用了QQ的SMTP服务,需要在邮箱中设置开启SMTP服务
    'port':25, #端口
    'user':'hacker@qq.com',#发送人
    'pwd':'hacker', #发送人的密码
    'send_to':'sniper@qq.com', #收件者
}
msg_options={
    'user':'hacker', #短信平台的用户名
    'pwd':'74110', #短信平台的密码
    'phone':'12345678910', #需要发短信的电话号码
}
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='服务器:%s挂了!状态码:%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:服务器: %s 挂了 !状态码:%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
    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

希望本文提供的代码示例能对您的Python程序设计工作提供有益帮助。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。