0基础上手python编程,实践URL监控+企业微信机器人告警

0基础上手python编程,实践URL监控+企业微信机器人告警

王忘杰
2023-05-10 / 0 评论 / 270 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年05月10日,已超过323天没有更新,若内容或图片失效,请留言反馈。

全民制作人大家好,我是学习python两天半的练习生王忘杰,喜欢路由交换、linux、网络安全,开整!这是我的第二篇0基础python文章,请大家支持,谢谢~

开发思路
用于监控指定的URL,在我的场景中,我是从腾讯VPS上监控公司宽带出口,当URL访问超时时,即为宽带故障。
设计思路很简单,访问失败发送告警,访问成功发送恢复通知,同时要使用配置文件进行配置,防止持续重复告警。

绘制开发流程图
lhh9pp5r.png

使用python语言实现

#!/usr/bin/python3
import requests
import time
import json
import os


# 监测URL是否正常响应
def url_check(url):
    # 当前时间
    check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    try:
        # 请求URL, 设置3s超时, 忽略SSL证书
        r = requests.get(url, timeout=3, verify=False)
        if r.status_code == 200:
            fo = open(config,"r")
            line = fo.read(1)
            print(line)
            #判断配置文件内容
            if line == "1":
                print("发送报警")
                fo.close()
                fo = open(config, "w")
                fo.write('0')
                print("配置重置为0")
                # 请求响应状态
                msg = "监控的URL:%s%sURL恢复状态正常:%s%s监测时间:%s" % (
                url, "\n\n", r.status_code, "\n\n", check_time)
                # 推送消息
                yun_push(msg)
            else:
                print("当前配置为",line)
                fo = open(config, "w")
                fo.write('0')
                print("配置重置为0")
        else:
            fo = open(config, "r")
            line = fo.read(1)
            print(line)
            if line == "1":
                print("退出程序")
            else:
                print("发送报警")
                fo.close()
                fo = open(config, "w")
                fo.write('1')
                print("配置重置为1")
                # 请求响应状态
                msg = "监控的URL:%s%sURL访问异常:%s%s监测时间:%s" % (
                    url, "\n\n", r.status_code, "\n\n", check_time)
                # 推送消息
                yun_push(msg)
    except:
        fo = open(config, "r")
        line = fo.read(1)
        print(line)
        if line == "1":
            print("退出程序")
        else:
            print("发送报警")
            fo.close()
            fo = open(config, "w")
            fo.write('1')
            print("配置重置为1")
            # 请求响应状态
            msg = "监控的URL:%s%sURL访问失败,无法连接%s监测时间:%s" % (
                url, "\n\n", "\n\n", check_time)
            # 推送消息
            yun_push(msg)

def yun_push(content):
    url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=用自己的'
    s = json.dumps({'msgtype': 'text', 'text': {"content" : content}})
    print(requests.post(url, data=s).text)

if __name__ == '__main__':
    #判断配置文件是否存在,不存在则生成配置文件并退出,配置文件则存在执行
    config = './baidu.config'
    if not os.path.exists(config):
        print("配置文件不存在")
        file = open(config,'w')
        file.close()
        print("配置文件已生成")
    else:
        print("配置文件存在,执行URL检测")
        url_check("https://www.baidu.com/")

运行效果
lhh9wtno.png

正式使用
在VPS部署python脚本,并设置定时任务即可

7

评论

博主关闭了所有页面的评论