python监控网站运行异常并发送邮件的方法

yipeiwu_com6年前Python基础

本文实例讲述了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使用Pandas库实现MySQL数据库的读写

Python使用Pandas库实现MySQL数据库的读写

本次分享将介绍如何在Python中使用Pandas库实现MySQL数据库的读写。首先我们需要了解点ORM方面的知识 ORM技术 对象关系映射技术,即ORM(Object-Relatio...

windows下Anaconda的安装与配置正解(Anaconda入门教程) 原创

windows下Anaconda的安装与配置正解(Anaconda入门教程) 原创

一、下载anaconda 第一步当然是下载anaconda了,官方网站的下载需要用迅雷才能快点,或者直接到清华大学镜像站下载。当然这里推荐【听图阁-专注于Python设计】下载,下载地址...

python三引号输出方法

python三引号输出方法

和C语言一样,引号属于特殊功能字符,不能够像普通字符那样直接通过print打印,需要进行一些处理,比如说反斜杠转义等。这里介绍几种打印三引号的方法,希望对需要的朋友有用。 1、第一中方法...

Python定时任务工具之APScheduler使用方式

APScheduler (advanceded python scheduler)是一款Python开发的定时任务工具。 文档地址 apscheduler.readthedoc...

Python3安装pip工具的详细步骤

Python3安装pip工具的详细步骤

前几天安装Python的时候没有装上pip工具,所以只能现在手动安装了。 首先,访问https://bootstrap.pypa.io/get-pip.py这个网址,然后Ctrl+S将g...