在飞书群中@机器人,通过问题ID修改zabbix的确认选项。改改就能用

利用飞书应用,在群中@机器人,通过问题ID修改zabbix的确认选项
在这里插入图片描述

在这里插入图片描述

zabbix首页
在这里插入图片描述

# -*- coding: utf-8 -*-
import json
import requests
from flask import Flask,request
import hashlib
import base64
from Crypto.Cipher import AES

#涉及文档连接
#https://open.feishu.cn/document/ukTMukTMukTM/uYDNxYjL2QTM24iN0EjN/event-subscription-configure-/request-url-configuration-case?lang=zh-CN
#https://open.feishu.cn/apps/cli_a1fccd65ed79900c/event
#
#https://open.feishu.cn/document/ukTMukTMukTM/uYDNxYjL2QTM24iN0EjN/event-subscription-configure-/encrypt-key-encryption-configuration-case


#飞书后台查看飞书应用,用于事件定阅.需要修改
app_id = "cli_"
app_secret = "7SS"
Encrypt_Key = "WW1bm"

#zabbix后台查看,需要修改
zabbix_url = 'http://zabbix1.landspace.com/zabbix/api_jsonrpc.php'
zabbix_auth = "21bb15119c22bc05"

#群中添加两个机器人,一个负责接收@机器人消息,一个负责发送成功或者失败。
#下面这个是发送成功或失败的。需要修改
feishu_webhook_url = "https://open.feishu.cn/open-apis/bot/v2/h"

class  AESCipher(object):
    def __init__(self, key):
        self.bs = AES.block_size
        self.key=hashlib.sha256(AESCipher.str_to_bytes(key)).digest()
    @staticmethod
    def str_to_bytes(data):
        u_type = type(b"".decode('utf8'))
        if isinstance(data, u_type):
            return data.encode('utf8')
        return data
    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s) - 1:])]
    def decrypt(self, enc):
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return  self._unpad(cipher.decrypt(enc[AES.block_size:]))
    def decrypt_string(self, enc):
        enc = base64.b64decode(enc)
        return  self.decrypt(enc).decode('utf8')

def feishu_jiemi(miwen,Encrypt_Key):
    cipher = AESCipher(Encrypt_Key)
    return cipher.decrypt_string(miwen)

def get_tenant_access_token():
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    payload = json.dumps({
        "app_id": app_id,
        "app_secret": app_secret
    })

    headers = {
      'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    tenant_access_token_str = eval(response.text)
    tenant_access_token = tenant_access_token_str.get('tenant_access_token')

    return tenant_access_token

def get_feishu_ip():
    url = "https://open.feishu.cn/open-apis/event/v1/outbound_ip?page_size=10"
    payload = ""
    headers = {"Authorization": "Bearer " + get_tenant_access_token()}
    response = requests.request("GET", url, headers=headers, data=payload)
    feishu_ip_dic = eval(response.text)
    feishu_ip_list = list(feishu_ip_dic.get("data").get("ip_list"))
    return feishu_ip_list

def zabbix_queren(eventid,message="确认"):

    url = zabbix_url
    header = {'Content-Type': 'application/json-rpc'}
    data = {
               "jsonrpc": "2.0",
               "method": "event.acknowledge",
               "params": {
               "eventids": eventid,
               "action": 6,
               "message": message,
               },
               "auth": zabbix_auth,
               "id": 1
           }

    datajs_hostid = json.dumps(data).encode('utf-8')
    requests.post(url, headers=header, data=datajs_hostid)

def send_message(message):
    # 个人测试飞书机器人
    url = feishu_webhook_url
    payload_message = {
        "msg_type": "text",
        "content": {
            "text": message
        },
    }
    headers = {
        'Content-Type': 'application/json'
    }

    requests.request("POST", url, headers=headers, data=json.dumps(payload_message))

def userid_get_name(user_id):
    url = "https://open.feishu.cn/open-apis/contact/v3/users/" + user_id + "?department_id_type=department_id&user_id_type=user_id"
    payload = ''
    headers = {
        'Authorization': "Bearer " + get_tenant_access_token()
    }

    response = requests.request("GET", url, headers=headers, data=payload)

    user_name = response.json().get('data').get('user').get('name')
    return user_name

app = Flask(__name__)
@app.route('/', methods=['POST'])
def post_zabbix():
    if request.method == 'POST':
        headers_ip = request.remote_addr
        # headers_ip = request.headers['X-Real-Ip']
        feishu_ip = str(headers_ip)
        if feishu_ip in get_feishu_ip():
            #获取飞书发来得数值。txt类型为dict
            txt = request.get_json()
            #从中获取到加密后的值
            data = txt.get('encrypt')
            #解密,类型为str
            get_josn = feishu_jiemi(data,Encrypt_Key)
            #解密后的值(str),变成dict
            # print(get_josn)
            get_josn = eval(get_josn)
            # print(get_josn)

            #获取用户输入的内容
            message_josn = get_josn.get('event').get('message').get('content')
            message_dic = eval(message_josn)
            message_at = message_dic.get("text")
            message = message_at.split(" ")
            message = message[1]


            #获取用户user_id
            user_id = get_josn.get('event').get('sender').get('sender_id').get('user_id')
            user_name = userid_get_name(user_id)

            try:
                zabbix_queren(message,user_name)
                send_message(user_name + ':成功暂停问题,问题ID为:' + message)
            except:
                send_message(user_name + ':暂停问题失败,问题ID为:' + message)

        return 'success', 200

        # challenge = get_josn.get("challenge")
        # #新建dict,从新变成json
        # ret_chall_dic = {"challenge": challenge}
        # ret = json.dumps(ret_chall_dic)
        # #按文档要求返回JSON数值
        # return ret

    # if request.method == 'GET':
    #     # print(request.headers)
    #     headers = request.headers['X-Real-Ip']
    #     # print(headers)
    #     return '<h1>'+ str(headers) + '</h1>'

if __name__ == "__main__":
    # from gevent import pywsgi
    # server = pywsgi.WSGIServer(('0.0.0.0',3000),app)
    # server.serve_forever()
    app.run(host="0.0.0.0", port=3000, debug=True, threaded=True)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信飞翔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值