加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:22:49 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 一个简单的python开发的监控程序,当指定网页状态不正常是通过smtp发送通知邮件 #!/usr/bin/env python# -*- coding: UTF-8 -*-#author libertyspy#li

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

一个简单的python开发的监控程序,当指定网页状态不正常是通过smtp发送通知邮件
#!/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':'[email?protected]',#发送人
    'pwd':'hacker',#发送人的密码
    'send_to':'[email?protected]',#收件者
}
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,status):
    smtp = smtplib.SMTP()
    smtp.connect(mail['server'],mail['port'])
    smtp.login(mail['user'],mail['pwd'])
    msg="From:%srTo:%srSubject:服务器: %s 挂了 !状态码:%srn" 

         % (mail['user'],mail['send_to'],status)
    smtp.sendmail(mail['user'],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,status)
    else:
        pass

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读