zabbix Sends WeChat Alerts with Pictures

Keywords: Linux Zabbix Session JSON Python

zabbix Sends WeChat Alerts with Pictures

2.1 Realization Ideas

2.2 Preparing the environment

  • The script uses python scripts, running in python 2.7.5
  • Dependent libraries are installed in advance: requests

2.3 ×××tid,secret

This section allows you to see a detailed description of the previous article without a diagram

2.4 Script Implementation

_author__ = 'zhangdongdong'
import requests, json
import urllib3
import smtplib,sys,os,time,re,requests
from email.mime.image import MIMEImage
if sys.getdefaultencoding() != 'utf-8':
class WechatImage(object): # According to the Enterprise WeChat api interface document, define a class using mpnews type,

    def get_token(self, corpid, secret): # Get token
        url = ""
        data = {"corpid": corpid,
                "corpsecret": secret}
        r = requests.get(url=url, params=data, verify=False)
        token = r.json()['access_token']
        return token

    def get_image_url(self, token, path): # Upload a temporary material picture and return to media_id
        url = "" % token
        data = {"media": open(path, 'rb')}
        r =, files=data)
        dict_data = r.json()
        return dict_data['media_id']
    def get_messages( self,subject,content,path): #Define parameter dictionary in mpnews type
        data = ''
        messages = {}
        body = {}
        token = self.get_token(corpid, secret)
        image = self.get_image_url(token, path)
        content_html += "<br/> <img src=''>" % (token, image)
        body["title"] = subject
        body['digest'] = content
        body['content'] = content_html
        body['thumb_media_id'] = image
        data = []
        messages['articles'] = data
        return messages
    def send_news_message(self, corpid, secret,to_user, agentid,path): #Define data to send mpnews type
        token = self.get_token(corpid, secret)
        messages = self.get_messages( subject, content,path)
        url = "" % token
        data = {"toparty": to_user,                                 # User Account Number in Enterprise Number
                "agentid": agentid,                             # Application id in enterprise number
                "msgtype": "mpnews",
                "mpnews": messages,
                "safe": "0"}
        headers = {'content-type': 'application/json'}
        data_dict = json.dumps(data, ensure_ascii=False).encode('utf-8')
        r =, headers=headers, data=data_dict)
        return r.text
def text_to_html(text): #Convert the text field of the message content to HTML format
    #Store mail content in a list as a list element per line
    for i in d:
        i='' + i + '<br>'
        html_text+=i + '\n'
    #Add html wrap tags to each element of the list
    return html_text
def get_itemid():
    #Get alert itemid'Monitor ID:(\d+)',sys.argv[3]).group(1)
    return itemid
def get_graph(itemid):
    #Get the alarm chart and save it
    session=requests.Session()   #Create a session session session
        #Define Request Header

        payload = {
        "enter":"Sign in",
        #Define incoming data,headers=loginheaders,data=payload)
        #Log on
            "from" :"now-10m",
            "to" : "now",
            "itemids" : itemid,
            "width" : "290", #Picture height and width parameters
            "height" : "40",
        #Define parameters for getting pictures
        #Send get request for picture data
        time_tag=time.strftime("%Y%m%d%H%M%S", time.localtime())
        #Save picture name with alarm time
        graph_name = os.path.join(graph_path, graph_name)
        #Save pictures using absolute paths
        with open(graph_name,'wb') as f:
            #Write the captured picture data to a file
        return graph_name
    except Exception as e:
        return False
if __name__ == '__main__':
    user='Admin'    #Define zabbix user name
    password='zabbix'    #Define zabbix user isecret
    graph_path='/usr/lib/zabbix/alertscripts/graph/'   #Define the path to store pictures, pictures need to be cleaned up regularly
    graph_url=''#Define the url of the chart
    loginurl=" "#Defines the url of the login
    path =get_graph(itemid)
    to_user = str(sys.argv[1]) 
    subject = str(sys.argv[2]) 
    content = str(sys.argv[3])
    corpid= "xxxxx"
    secret = "xxxxxxx"
    agentid = "1000002"
    wechat_img = WechatImage()
    wechat_img.send_news_message(corpid, secret,to_user, agentid, path)

2.5 Define the type of alarm medium

Open the ZABBIX monitoring web, select the alarm media type in the management menu, create the media type, select the script, fill in the name of the microstrip diagram script just written, script parameters, and add

Open the user in management, click on the user who needs to set up the mail alarm, add the alarm medium in the alarm medium, select the type just defined in the pop-up box, fill in the Department id created in the enterprise micro-mail, and add the last one

2.6 Define warning actions

  • Click on the action in the Configuration menu, create the action, and fill it out according to the picture
 Default Title 
Zabbix Warning:
Secondary server: {HOSTNAME} occurred: {TRIGGER.NAME} failure!
Monitoring ID:{ITEM.ID}
Alert Host: {HOST.NAME}
Alert Host: {HOST.IP}
Warning time: {EVENT.DATE} {EVENT.TIME}
Alert information: {TRIGGER.NAME}
Alert item: {TRIGGER.KEY}
Question details: {ITEM.NAME}:{ITEM.VALUE}
Recovery operation
 Zabbix Warning:
Secondary server: {HOST.NAME} occurred: {TRIGGER.NAME} recovered!
Monitoring ID:{ITEM.ID}
Alert Host: {HOST.NAME}
Alert Host: {HOST.IP}
Warning time: {EVENT.DATE} {EVENT.TIME}
Alert information: {TRIGGER.NAME}
Alert item: {TRIGGER.KEY}
Question details: {ITEM.NAME}:{ITEM.VALUE}

2.7 Test results

You can trigger an alarm test effect manually, and you can receive an alarm with a picture on your mobile phone. You can also see a picture of history by clicking on the page after the message

Huan X X X Chen Shifu"

Posted by Toby on Thu, 07 Nov 2019 13:51:47 -0800