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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

关于pip的安装,更新,卸载模块以及使用方法(详解)

在Python的学习过程中,肯定会遇到很多安装模块的地方,可以使用easy_install安装,但是easy_install相对于pip而言,最大的缺陷就是它所安装的模块是不能够卸载的,...

详解如何从TensorFlow的mnist数据集导出手写体数字图片

详解如何从TensorFlow的mnist数据集导出手写体数字图片

在TensorFlow的官方入门课程中,多次用到mnist数据集。 mnist数据集是一个数字手写体图片库,但它的存储格式并非常见的图片格式,所有的图片都集中保存在四个扩展名为idx3-...

Python函数式编程指南(一):函数式编程概述

1. 函数式编程概述 1.1. 什么是函数式编程? 函数式编程使用一系列的函数解决问题。函数仅接受输入并产生输出,不包含任何能影响产生输出的内部状态。任何情况下,使用相同的参数调用函数始...

对python中大文件的导入与导出方法详解

1、csv文件的导入和导出 通过一个矩阵导出为csv文件,将csv文件导入为矩阵 将csv文件导入到一个矩阵中 import numpy my_matrix = numpy.lo...

python找出完数的方法

如下所示: # -*- coding: utf-8 -*- # 要求:用python方法找出1000以内的所有完数,并输出。 def f(n): list = [] for i...