Zabbix configures DingTalk's alarm function with pictures

Zabbix configures DingTalk's alarm function with pictures

Implementation ideas:

First of all, the alarm information must have itemid, which is a prerequisite. According to the parameters passed in the information, use regular matching to itemid to build a session, or use cookies to log in. Request pictures according to itemid and save the obtained pictures locally. Since the markdown picture link needs to be accessible, my zabbix is ​​in the intranet, so the picture needs to be uploaded to the image bed or to a web server with a public network IP. I uploaded it to my personal server here. Convert the alarm information into markdown syntax format to construct a request. Use DingTalk's webhook to send messages and set up DingTalk robots

DingTalk robot needs to be set up for security. Here I define the keyword "notification", which means that the message sent must contain this keyword.

Script implementation: Since the image needs to be copied from the local to the remote, the password-free configuration needs to be done in advance. The script is executed by the zabbix user. It is best to set the security policy of the Web server directory.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests,time
import json,sys,re,os

zabbixserver_url = 'http://192.168.99.200/index.php'
#Define the remote web server address and copy the image to the remote web directory pname_path='http://47.103.15.51/dingding_pic/'
#Define the obtained image address testUrl = "http://192.168.99.200/chart.php"
host='192.168.99.200'
def get_itemid():
  itemid=re.search(r'ITEM ID:(\d+)',sys.argv[2]).group(1)
  return itemid
def get_picture(itemid,pname):
  #Build a session, or you can build it once and then use cookies to log in myRequests = requests.Session()
  try:
    loginHeaders = {
      "Host": host,      
      "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" 
    }
    # Build the information needed for login playLoad = {
      "name": "Admin",
      "password": 'zabbix',
      "autologin": "1",
      "enter": "Sign in",
    }
    myRequests.post(url=zabbixserver_url, headers=loginHeaders, data=playLoad)
    testUrlplayLoad = {
      "from": "now-10m",
      "to": "now",
      "itemids": itemid,
      "width": "700",
    }
    testGraph = myRequests.get(url=testUrl,params=testUrlplayLoad)
    IMAGEPATH = os.path.join('/usr/lib/zabbix/alertscripts/dingding_pic/', pname)
    #Write the acquired image data into a file with open(IMAGEPATH,'wb') as f:
      f.write(testGraph.content)
    os.system("sudo scp %s [email protected]:/usr/share/nginx/html/dingding_pic" %IMAGEPATH) 
    pname_url = pname_path+pname
    return pname_url
  except Exception as e:
    print(e)
    return False

#Construct a request to send a message def send_msg(pname_url,info3):
  headers = {'Content-Type': 'application/json; charset=utf-8'}
  print(info3)
  data = {
    "msgtype": "markdown",
    "markdown": {
      "title": info1,
      "text": "## Notice:\n"+info3+"![screenshot](%s)\n"%(pname_url)

    },
    "at":{
      "atMobiles": reminders,
      "isAtAll": False,
    },
    }
  r = requests.post(url=webhook_url,json=data,headers=headers)
  print(r.text)
#Format the alarm information def info_text():
  new_text = ""
  x = info2.split('\n')
  for i in x:
    if re.search('ITEM ID',str(i)):
      pass
    else:
      new_text+="- "+str(i)+('\n')
  print(type(new_text)) 
  return new_text

if __name__ == '__main__':
  #Write the alarm information into the log os.system("echo hello >> /tmp/syslog.md")  
  pname = str(int(time.time()))+'.png'
  info1 = str(sys.argv[1])
  info2 = str(sys.argv[2])
  info3 = info_text()

  with open('/tmp/syslog.md','a') as f:
    f.write(info1)
    f.write(info2)
    f.close()
  reminders = []
  webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=771ded387e6be652c51a2b6c83cade4e048e3da4fdfe128f1db6b124b87df18a'
  itemid = get_itemid()   
  pname_url=get_picture(itemid,pname)
  print(pname_url)
  send_msg(pname_url,info3)

Define the alarm media type. Open the Zabbix monitoring web, select Alarm Media Type in the Management menu, Create Media Type, select Script, fill in the name of the email with picture script just written, zabbix_email_pic.py, script parameters, and finally add

Open the user in the management, click the user for whom you want to set up email alerts, then add the alarm medium in the alarm medium, select the type you just defined in the pop-up box, customize the recipient, and finally add

Defining Alert Actions

Click on the action in the configuration menu, create an action, and then fill it out according to the picture.

Action Default Title Zabbix Notice: Server: {HOSTNAME} has: {TRIGGER.NAME} failure!
ITEMID:{ITEM.ID}
Alarm host:{HOST.NAME}
Alarm host:{HOST.IP}
Alarm time: {EVENT.DATE} {EVENT.TIME}
Alarm level:{TRIGGER.SEVERITY}
Warning information: {TRIGGER.NAME}
Alarm item:{TRIGGER.KEY}
Question details:{ITEM.NAME}:{ITEM.VALUE}
Current status:{TRIGGER.STATUS}:{ITEM.VALUE}
Event ID: {EVENT.ID}
Recovery operation Zabbix reported: Server: {HOST.NAME} occurred: {TRIGGER.NAME} has been restored!
ITEMID:{ITEM.ID}
Alarm host:{HOST.NAME}
Alarm host:{HOST.IP}
Alarm time: {EVENT.DATE} {EVENT.TIME}
Alarm level:{TRIGGER.SEVERITY}
Warning information: {TRIGGER.NAME}
Alarm item:{TRIGGER.KEY}
Question details:{ITEM.NAME}:{ITEM.VALUE}
Current status:{TRIGGER.STATUS}:{ITEM.VALUE}
Event ID: {EVENT.ID} 



Final result

You can manually trigger an alarm to test the effect


At this point, Zabbix's WeChat, email, and DingTalk alarms with pictures have been configured.

Summarize

The above is the editor's introduction to the Zabbix configuration DingTalk with picture alarm function. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!
If you find this article helpful, please feel free to reprint it and please indicate the source. Thank you!

You may also be interested in:
  • Zabbix3.0 email alarm configuration
  • How to use python script to send alarm emails in zabbix
  • Zabbix implements WeChat alarm function
  • Detailed explanation of WeChat alarm Zabbix implementation
  • Zabbix email alarm setting method

<<:  Detailed explanation of creating a data table in MySQL and establishing primary and foreign key relationships

>>:  Implementation of webpack-dev-server to build a local server

Recommend

How to simulate enumeration with JS

Preface In current JavaScript, there is no concep...

Is a design that complies with design specifications a good design?

In the past few years of my career, I have writte...

JavaScript two pictures to understand the prototype chain

Table of contents 1. Prototype Relationship 2. Pr...

Web Design Tutorial (7): Improving Web Design Efficiency

<br />Previous article: Web Design Tutorial ...

Example of how to mosaic an image using js

This article mainly introduces an example of how ...

Solution to MySQL connection exception and error 10061

MySQL is a relational database management system ...

Detailed explanation of the Sidecar mode in Docker Compose

Table of contents What is Docker Compose Requirem...

Vue: Detailed explanation of memory leaks

What is a memory leak? A memory leak means that a...

mysql5.7.17 installation and configuration example on win2008R2 64-bit system

123WORDPRESS.COM has explained to you the install...

How to assign a public IP address to an instance in Linux

describe When calling this interface, you need to...

Disabled values ​​that cannot be entered cannot be passed to the action layer

If I want to make the form non-input-capable, I se...

Detailed explanation of Truncate usage in MySQL

Preface: When we want to clear a table, we often ...

Summary of commonly used commands for docker competition submission

Log in to your account export DOCKER_REGISTRY=reg...