• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

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

python 水墨上仙 1338次浏览

一个简单的python开发的监控程序,当指定网页状态不正常是通过smtp发送通知邮件

转自:http://www.lastme.com/

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#author  libertyspy
#link    http://www.lastme.com

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监控网站运行异常并发送邮件
喜欢 (0)
加载中……