ZABBIX docking flybook realizes alarm notification with pictures

Posted by Flames on Fri, 21 Feb 2020 15:33:55 +0100

Flybook provides rich api to realize message notification, including text message, picture message and rich text message. This paper introduces the use of flybook api to send rich text message. The following is the implementation idea
API address: https://open.feishu.cn/document/ukTMukTMukTM/uITNz4iM1MjLyUzM

Implementation ideas

1. Get the monitoring item id according to the rule, and define the alarm information in the action
2. Obtain the image address according to the acquired monitoring item id construction request and download it to the local
3. Three authorization certificates need to be obtained

  • App > access > token: access the interface related to app resources.
  • Tenant? Access? Token: access the interface related to enterprise resources.
  • User? Access? Token: access to user resource related interfaces.

4. According to the mobile phone number of the receiver of zabbix alarm, obtain the user ﹣ ID, which can be used for the next @ related responsible person in the group, or directly sent to a responsible person
5. Chat ABCD ID is used to send to the specified group. Here I provide two methods to obtain chat ABCD ID, which will be described later
6. Upload local pictures to the flybook, and obtain img_key, image_key to send picture information
7. The zabbix alarm message is passed in, and the relevant person in charge of AIT sends it to the fly book group or individual

Get itemID

Using regular matching to match itemID in alarm information

def get_itemid():
    #Get the itemid of the alarm
    itemid=re.search(r'ITEM ID:(\d+)',sys.argv[3]).group(1)
    return itemid

Get alarm picture address

According to the incoming itemID, construct a request to download the alarm picture and save it locally

def get_graph(itemid):
    #Get the chart of the alarm and save it
    session=requests.Session()   #Create a session
    try:
        loginheaders={            
        "Host":host,            
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
        }
        #Define request headers

        payload = {            
        "name":user,
        "password":password,  
        "autologin":"1",            
        "enter":"Sign in",
        }
        #Define incoming data
        login=session.post(url=loginurl,headers=loginheaders,data=payload)
        #Login
        graph_params={
            "from" :"now-10m",
            "to" : "now",           
            "itemids" : itemid,                       
            "width" : "400",
        }
        #Define parameters for getting pictures
        graph_req=session.get(url=graph_url,params=graph_params)
        #Send get request to get picture data
        time_tag=time.strftime("%Y%m%d%H%M%S", time.localtime())
        graph_name='baojing_'+time_tag+'.png'
        #Save with alarm time as picture name
        graph_name = os.path.join(graph_path, graph_name)
        #Use absolute path to save picture
        with open(graph_name,'wb',) as f:
            f.write(graph_req.content)
            #Write the acquired picture data to the file

        return graph_name

    except Exception as e:        
        print (e)        
        return False

Get authorization certificate

1. Get App ID and App Secret

Log in the developer background, and create enterprise built applications on the "my applications" page. Enter the enterprise self built application details page to obtain the App ID and App Secret.

2. Obtain tenant access token

One way is to get it through enterprise self built applications, and the other way is to get it through app store applications. Here I use the first way to create apps directly

3. After the application is created, it can be obtained according to the APP ID and App Secret construction request

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

Get user ID

The user ID can be obtained according to the registered mobile phone number or mailbox. You can define the user's mobile phone number in zabbix, and then pass in the parameter to obtain the 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

Get chat ID

Here, I provide two methods to obtain chat ABCD ID, one is to add robots to the group and obtain chat ABCD ID in the group information; the other is to create a group chat through robots to obtain group information, of course, there are other methods, which I will only introduce here. I will use the first method to obtain chat ABCD ID

First, add robots to group chat

Construct a request to get chat ID

def getchatid(tenant_access_token):
    #Get 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

Upload the alarm picture to the flybook through api

By uploading the alarm picture, an image_key will be obtained to send the picture information of the rich text message

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']

Send a message to the users of flybook group or flybook

Four parameters are required here, namely user ID, chat ID, tenant access token and image key, which can be sent by passing in alarm information

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"}
    #Send rich text messages to the group
    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)

Configure alarm action and receiver on ZABBIX

Configure alarm media type

Pay attention to the order of parameters

Configure receiving information for users

That is, the mobile number of the user's registered flybook

Configuration action

Alarm test

Here i disable one of the windows agent s for testing


The alarm with picture information will be added later. For the complete code, please visit github to organize the sunshade note
https://github.com/sunsharing-note/zabbix/blob/master/feishu_img.py

Welcome to pay attention to personal company name "master Chen without story"

Topics: Linux JSON Zabbix Session Mobile