飞书提供了丰富的api来实现消息的通知,包括文本消息、图片消息、富文本消息,本次介绍使用飞书api发送富文本消息,以下是实现思路 飞书API地址:https://open.feishu.cn/document/ukTMukTMukTM/uITNz4iM1MjLyUzM

实现思路

1.根据正则获取监控项id,需要在动作中定义报警信息 2.根据获取的监控项id构造请求获取图片地址,并下载到本地 3.需要获取三个授权凭证

  • app_access_token :访问App资源相关接口。
  • tenant_access_token :访问企业资源相关接口。
  • user_access_token :访问用户资源相关接口。

4.根据zabbix报警的收信人手机号获取user_id,用于后面在群里@相关负责人,或者直接发给某个责任人 5.chat_id用于发送给指定的群,这里我提供两种方法获取chat_id,后面会介绍 6.上传本地图片到飞书,并获取img_key,image_key用于发送图片信息 7.传入zabbix报警消息,并艾特相关负责人发送到飞书群里或者个人

获取itemID

利用正则匹配报警信息中的itemID

def get_itemid():
    #获取报警的itemid
    itemid=re.search(r'ITEM ID:(\d+)',sys.argv[3]).group(1)
    return itemid

获取报警图片地址

根据传入的itemID,构造请求下载报警图片,并保存到本地

def get_graph(itemid):
    #获取报警的图表并保存
    session=requests.Session()   #创建一个session会话
    try:
        loginheaders={            
        "Host":host,            
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
        }
        #定义请求消息头
        
        payload = {            
        "name":user,
        "password":password,  
        "autologin":"1",            
        "enter":"Sign in",
        }
        #定义传入的data
        login=session.post(url=loginurl,headers=loginheaders,data=payload)
        #进行登录
        graph_params={
            "from" :"now-10m",
            "to" : "now",           
            "itemids" : itemid,                       
            "width" : "400",
        }
        #定义获取图片的参数
        graph_req=session.get(url=graph_url,params=graph_params)
        #发送get请求获取图片数据
        time_tag=time.strftime("%Y%m%d%H%M%S", time.localtime())
        graph_name='baojing_'+time_tag+'.png'
        #用报警时间来作为图片名进行保存
        graph_name = os.path.join(graph_path, graph_name)
        #使用绝对路径保存图片
        with open(graph_name,'wb',) as f:
            f.write(graph_req.content)
            #将获取到的图片数据写入到文件中去
        
        return graph_name
    
    except Exception as e:        
        print (e)        
        return False

获取授权凭证

1.获取 App ID 和 App Secret

登录开发者后台,在“我的应用”页面创建企业自建应用。进入企业自建应用详情页,获取App ID和App Secret。

2.获取 tenant_access_token

一种方法是通过企业自建应用方式获取,另一种是通过应用商店应用获取,这里我使用第一种方法,直接创建应用即可

3.创建完应用后可根据APP ID和 App Secret构造请求获取

def gettenant_access_token():
    tokenurl="https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
    headers={"Content-Type":"application/json"}
    data={
        "app_id":"cli_9ec625abcdefg",
        "app_secret":"f716Gi27Yi25n5K0Wbafgwghhstv"

    }
    request=requests.post(url=tokenurl,headers=headers,json=data)
    response=json.loads(request.content)['tenant_access_token']
    return response

获取user_id

user_id可以根据注册的手机号或邮箱获取,可以在zabbix中定义用户的手机号,然后传入参数获取user_id

def getuserid(tenant_access_token):
    #mobiles="15101234584"
    userurl="https://open.feishu.cn/open-apis/user/v1/batch_get_id?mobiles=%s"%mobiles
    headers={"Authorization":"Bearer %s"%tenant_access_token}
    request=requests.get(url=userurl,headers=headers)
    response=json.loads(request.content)['data']['mobile_users'][mobiles][0]['user_id']
    return response

获取chat_id

这里我提供两种方法获取chat_id,一种是将机器人加入到群里,获取群信息中的chat_id;另一种是通过机器人创建群聊获取群信息,当然还有其他的方法,这里我就不过多介绍了,我将使用第一种方法来获取chat_id

首先将机器人加入到群聊

构造请求获取chat_id

def getchatid(tenant_access_token):
    #获取chatid
    chaturl="https://open.feishu.cn/open-apis/chat/v4/list?page_size=20"
    headers={"Authorization":"Bearer %s"%tenant_access_token,"Content-Type":"application/json"}
    request=requests.get(url=chaturl,headers=headers)
    response=json.loads(request.content)['data']['groups'][0]['chat_id']
    return response

通过api向飞书上传报警图片

通过上传报警图片,会获取到一个image_key,用于发送富文本消息的图片信息

def uploadimg(tenant_access_token,graph_name):
    with open(graph_name,'rb') as f:
        image = f.read()
    imgurl='https://open.feishu.cn/open-apis/image/v4/put/'
    headers={'Authorization': "Bearer %s"%tenant_access_token}
    files={
            "image": image
        }
    data={
            "image_type": "message"
        }
    
    resp = requests.post(
        url=imgurl,
        headers=headers,
        files=files,
        data=data)
    resp.raise_for_status()
    content = resp.json()
    return content['data']['image_key']

向飞书群里或者飞书用户发送消息

这里需要四个参数,分别是user_id、chat_id、tenant_access_token和image_key,并传入报警信息即可发送

def sendmes(user_id,chat_id,tenant_access_token,image_key):
    sendurl="https://open.feishu.cn/open-apis/message/v4/send/"
    headers={"Authorization":"Bearer %s"%tenant_access_token,"Content-Type":"application/json"}
    #向群里发送富文本消息
    data={
        "chat_id":chat_id,
        "msg_type":"post",
        "content":{
            "post":{
                "zh_cn":{
                    "title":subject,
                    "content":[
                        [
                        {
                            "tag": "text",
                            "un_escape": True,
                            "text": messages
                        },
                        {
                            "tag": "at",
                            "user_id": user_id

                        }
                    ],
                    [
                        {
                            "tag": "img",
                            "image_key": image_key,
                            "width": 700,
                            "height": 400
                        }
                    ]
                ]
            }
        }
    }
    }
  
    request=requests.post(url=sendurl,headers=headers,json=data)
    print(request.content)

在ZABBIX上配置报警动作及接收人

配置报警媒介类型

注意参数顺序不能乱

配置用户的接收信息

也就是用户注册飞书的手机号

配置动作

报警测试

这里我禁掉了其中一台windows的agent进行测试

后续会添加带有图片信息的报警,完整代码请访问github组织遮阳笔记 https://github.com/sunsharing-note/zabbix/blob/master/feishu_img.py


欢迎关注个人公号“没有故事的陈师傅”