python3监控网站在离线调用企业微信通知

创建三个文件

  • main.py
import time
import tools
import webhook

# 定义需要监控的服务关系字典
service_dict = {
    "test-baidu": "https://www.baidu.com/",
    "test-sina": "https://www.sina.com.cn/"
}

# 根据服务字典进行巡检
while True:
    for name, service in service_dict.items():
        # 获取状态码
        http_code = tools.get_status_code(service)
        # print(f"{name}的状态码为:{http_code}")
        # 判断有无异常,有则报警 无则结束
        if http_code == 200:
            print(f"{name}服务正常,状态码为:{http_code}")
        elif http_code == 401:
            print(f"{name}服务正常,状态码为:{http_code}")
        elif http_code == 502:
            webhook.send_msg(name, http_code, service)
        else:
            print(f"{name}服务正常,状态码为:{http_code}")
    time.sleep(360)

  • webhook.py
import requests
import json

wx_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=4794df11-557e-4690-xxxa-9bfaf4aca474"


def send_msg(name, http_code, service):
    """
    发送指定消息
    :param name:
    :param http_code:
    :param service:
    :return:
    """
    send_message = f"<font color=\"warning\"> {name} </font>服务离线,请相关同事注意。\n> 状态码:<font color=\"comment\"> {http_code} </font>\n> 链接:<font color=\"comment\"> [{service}]({service}) </font>"
    data = json.dumps({"msgtype": "markdown", "markdown": {"content": send_message}})
    r = requests.post(wx_url, data, auth=('Content-Type', 'application/json'))

  • tools.py
import requests


def get_status_code(url):
    """
    根据输入的url,获取对应的http状态码
    :param url: 需要测试的url
    :return: 状态码
    """
    res = requests.get(url)
    return res.status_code

启动main.py即可

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值