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

Detailed tutorial on installing VirtualBox and Ubuntu 16.04 under Windows system

1. Software Introduction VirtualBox VirtualBox is...

An example of how to optimize a project after the Vue project is completed

Table of contents 1. Specify different packaging ...

Steps to install MySQL 8.0.23 under Centos7 (beginner level)

First, let me briefly introduce what MySQL is; In...

Summary of @ usage in CSS (with examples and explanations)

An at-rule is a declaration that provides instruc...

How to deploy a simple c/c++ program using docker

1. First, create a hello-world.cpp file The progr...

JS implements random roll call system

Use JS to implement a random roll call system for...

Tutorial on installing PHP on centos via yum

First, let me introduce how to install PHP on Cen...

MySQL encryption and decryption examples

MySQL encryption and decryption examples Data enc...

Implementation of installing and uninstalling CUDA and CUDNN in Ubuntu

Table of contents Preface Install the graphics dr...

Jenkins packaging microservices to build Docker images and run them

Table of contents Environment Preparation start 1...

What hidden attributes in the form can be submitted with the form

The form elements with visibility=hidden and displ...

Some front-end basics (html, css) encountered in practice

1. The div css mouse hand shape is cursor:pointer;...

Detailed explanation of Vuex environment

Table of contents Build Vuex environment Summariz...

MYSQL's 10 classic optimization cases and scenarios

Table of contents 1. General steps for SQL optimi...