Python监控Nginx 4层7层状态

[root@acs-hk-ctos7-prod-01 scripts]# cat upstrem.py
#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2023/6/25 17:18
# @File    : nginx_upstram.py
# @Software: PyCharm

import requests
from urllib.request import urlopen
import os,socket,datetime,hashlib,base64,hmac,urllib
import time



def get_digest():
    timestamp = str(round(time.time() * 1000))
    #测试
    #secret = ''
    #生产
    secret = ''
    secret_enc = secret.encode('utf-8')  # utf-8编码
    string_to_sign = '{}\n{}'.format(timestamp, secret)  # 字符串格式化拼接
    string_to_sign_enc = string_to_sign.encode('utf-8')  # utf-8编码
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()  # HmacSHA256算法计算签名
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))  # Base64编码后进行urlEncode
    #  返回时间戳和计算好的编码拼接字符串,后面直接拼接到Webhook即可
    return f"&timestamp={timestamp}&sign={sign}"

def get_system_info():
    # 系统时间
    dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    # 系统公网IP
    ip = requests.get('http://ifconfig.me').text.strip()

    # 内网IP
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    local_ip = s.getsockname()[0]
    s.close()

    #系统load
    system_load=os.popen("uptime|awk '{print $NF,$NF-1,$NF-2}'")
    load=system_load.read().strip()

    host_name=socket.gethostname()
    return dt, ip, local_ip,load,host_name


class Send_Dingding:
    def __init__(self, title,upst,stra):
        self.title = title
        self.upst=upst
        self.stra=stra

    def send_dingnding(self):
        MSG = "**告警主题**:" + "\n" + self.title + "\n\n" \
        ">当前时间:" + "\n" + get_system_info()[0] + "\n\n"\
        " >当前主机名:"  + "\n" + get_system_info()[4] + "\n\n" \
         " >当前服务器IP:" + "\n" + get_system_info()[1] + "\n" + get_system_info()[2] +"\n\n" \
         " >当前系统load:" + "\n" + str(get_system_info()[3]) + "\n\n" \
        "七层异常:" + "\n" + "\n" + str(self.upst) + "\n\n"\
        "四层异常:" + "\n" + "\n" + str(self.stra) + "\n\n"\


        data = {
            "msgtype": "markdown",
            "markdown": {
                "title": self.title,
                "text": MSG,

            },
            "at": {
                "atMobiles": [
                    "@"
                ],
                "isAtAll": False
            }
        }

# 测试
        #webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token='
# 生产
        webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token='
# 利用requests发送post请求
        rec = requests.post(webhook_url + get_digest(), json=data)



class Get_target:
    def __init__(self, url):
        self.url = url

    def Get_Upstream_Target(self):
        upstre = requests.get(self.url)
        upstre_json_str = upstre.json()
        up_list=[]
        for up_stre in upstre_json_str["servers"]["http"]:
            if up_stre["status"] == "down":
                up_list.append([up_stre["upstream"],up_stre["name"],up_stre["status"]])
                #up_text="Upstream:{}\tstaus: {}\thost: {}".format(up_stre["upstream"], up_stre['status'],up_stre["name"])
        if len(up_list) == 0:
            return  "程序正常"
        else:
            return up_list


    def Get_Stream_Target(self):
        stream = requests.get(self.url)
        stream_json = stream.json()
        st_list=[]
        for strem in stream_json['servers']["stream"]:
            if strem["status"] == "down":
                st_list.append([strem["upstream"],strem["status"],strem["name"]])
                #return "stream: {}\tstatus: {} \thost: {}".format(strem["upstream"], strem["status"], strem["name"])
        if len(st_list) == 0:
            return  "程序正常"
        else:
            return st_list


if "__name__ == __main__":
    res = Get_target('http:///status?format=json')
    up = res.Get_Upstream_Target()
    st = res.Get_Stream_Target()

    if st and up != "程序正常":
        send=Send_Dingding("香港集群环境",up,st)
        send.send_dingnding()
    else:
        print("不告警")

 

posted @ 2023-07-20 20:07  地铁昌平线  阅读(3)  评论(0编辑  收藏  举报  来源