URL检测脚本
#!/usr/bin/python3.8 # -*- coding:UTF-8 -*- import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from concurrent.futures import ThreadPoolExecutor from southpark.function.conndb import condb import requests import json import time import re # res, resall = condb('SELECT `url` FROM `domain`;') res, resall = condb('SELECT `url` FROM `domain` WHERE addr="www" OR `nginx`=2;') def curl_url(domain): """ 获取url请求状态码 :param domain: 域名 :return: 状态码,url地址 """ url = 'https://{}'.format(domain) res = requests.get(url=url, headers={ 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 'accept': '*/*', 'Connection': 'close'}, timeout=(5, 5)) print(time.strftime("%Y-%m-%d %H:%M:%S") + " " + sys._getframe().f_code.co_name + " " + str( res.status_code) + " " + url) return res.status_code, url def send(data): """ 发送告警消息到飞书 :param data: 获取curl_url执行结果 :return: None """ code, url = data.result() if re.match('5', str(code)): data = {"msg_type": "post", "content": {"post": {"zh_cn": {"title": "业务告警", "content": [ [{"tag": "text", "text": "%s 无法访问" % (url)}, {"tag": "text", "text": " "}, {"tag": "text", "text": "状态码:%s" % (code)}]]}}}} headers = {"Content-Type": "application/json"} requests.post(url='https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxx', headers=headers, data=json.dumps(data)) def start(): # 创建4个线程 pool = ThreadPoolExecutor(max_workers=4) print(time.strftime("%Y-%m-%d %H:%M:%S") + " " + "开始执行监控脚本:" + os.path.basename(__file__)) for i in resall: time.sleep(0.2) # 不阻塞,通过回调函数,获取curl_url函数的执行结果,curl_url函数名称,i.get('url')函数参数 pool.submit(curl_url, i.get('url')).add_done_callback(send) pool.shutdown(wait=True) print(time.strftime("%Y-%m-%d %H:%M:%S") + " " + "监控脚本执行完成") if __name__ == '__main__': start()