Zabbix essay: enterprise wechat applet alarm

This paper uses enterprise wechat to alarm. However, this method has an important premise. Zabbix Server needs the ability to access the external network, and the receiving end also needs the ability to access the Internet.

text

The environment of this article is python3 and python2. If you encounter problems, you can contact me in time.

Article environment

  • Zabbix Server 6.0 LTS RC2
  • Python 3

Enterprise wechat

Log in to the enterprise wechat background

In the application management menu, select Create application

You need to set the visible range here

After creation, you can view the AgentId, and the Secret needs to be viewed by logging in to the client or mobile client

So there are four messages we should get from now on

  • corpid
  • corpsecret
  • agentid
  • Department ID

Code part

According to the above part, we need to modify the four information of the script

#!/usr/bin/python2
#_*_coding:utf-8 _*_
import urllib,urllib2
import json
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
def gettoken(corpid,corpsecret):
    gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
    print  gettoken_url
    try:
        token_file = urllib2.urlopen(gettoken_url)
    except urllib2.HTTPError as e:
        print e.code
        print e.read().decode("utf8")
        sys.exit()
    token_data = token_file.read().decode('utf-8')
    token_json = json.loads(token_data)
    token_json.keys()
    token = token_json['access_token']
    return token
def senddata(access_token,user,subject,content):
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    send_values = {
        "touser":"$1",   
        "toparty":"Change to your department ID",        
        "msgtype":"text",     
        "agentid":"Change to your agentid",  
        "text":{
            "content":subject + '\n' + content
           },
        "safe":"0"
        }
    send_data = json.dumps(send_values, ensure_ascii=False).encode('utf-8')
    send_request = urllib2.Request(send_url, send_data)
    response = json.loads(urllib2.urlopen(send_request).read())
    print str(response)

if __name__ == '__main__':
    user = str(sys.argv[1])     
    subject = str(sys.argv[2])  
    content = str(sys.argv[3])  

    corpid =  'Change it to yours corpid'     
    corpsecret = 'Change it to yours corpsecret'
    accesstoken = gettoken(corpid,corpsecret)
    senddata(accesstoken,user,subject,content)
#!/usr/bin/python3
#_*_coding:utf-8 _*_
import urllib.request
import json
import sys

def gettoken(corpid,corpsecret):
    gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
    print  (gettoken_url)
    try:
        token_file = urllib.request.urlopen(gettoken_url)
    except urllib.error.HTTPError as e:
        print (e.code)
        print (e.read().decode("utf8"))
        sys.exit()
    token_data = token_file.read().decode('utf-8')
    token_json = json.loads(token_data)
    token_json.keys()
    token = token_json['access_token']
    return token

def senddata(access_token,user,subject,content):

    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    send_values = {
        "touser":"$1",   
        "toparty":"Change to your department ID",        
        "msgtype":"text",     
        "agentid":"Change to your agentid",  
        "text":{
            "content":subject + '\n' + content
           },
        "safe":"0"
        }
#    send_data = json.dumps(send_values, ensure_ascii=False)
    send_data = json.dumps(send_values, ensure_ascii=False).encode('utf-8')
    send_request = urllib.request.Request(send_url, send_data)
    response = urllib.request.urlopen(send_request)
    msg = response.read()
    print ("returned value : " + str(msg))


if __name__ == '__main__':
    user = str(sys.argv[1])     
    subject = str(sys.argv[2])  
    content = str(sys.argv[3])  

    corpid =  'Change to your corpid'     
    corpsecret = 'Change it to yours corpsecret'
    accesstoken = gettoken(corpid,corpsecret)
    senddata(accesstoken,user,subject,content)

Copy script to your system

By default, CentOS 7 is python2 and CentOS 8 is python3 Create a wechat Txt file, which is to avoid the coding format problem of Windows and Linux

touch wechat.txt 
vim wechat.txt

After completing the modification, change the suffix of the file to py

mv wechat.txt wechat.py

Test script

First give execution permission, and then execute the script to view the status

chmod +x wechat.py
./wechat.py 1 1 1 

Zabbix section

Query alarm script directory

By default, the directory is annotated (as shown in the figure below). It is recommended to cancel the annotation and restart the Zabbix Server service.

cat /etc/zabbix/zabbix_server.conf | grep AlertScriptsPath

Move script to specified directory

mv wechat.py /usr/lib/zabbix/alertscripts

Zabbix front end

Create alarm media path as management – > alarm media type – > create alarm media type

Alarm media configuration

First, select the script type and define its own name. The script name is the name of the script placed in the specified directory. It must correspond. The script parameters correspond to the order in python one by one. There are three parameters in python: user < – > {alert. SendTo}, subject < – > {alert. Subject}, content < – > {alert. Message}, and the following macros are fixed values.

The front-end variables are closely related to the back-end script. If there are only two parameters in the Python script (sys.argv []), you only need to write two.

Go to Message templates (the function here is message notification template, which contains some variables, that is, what needs to be included in the alarm, and alarm failure will occur if it is not filled in). Create a notification template, click add, and there will be some built-in templates by default. There is no need to set here. You can create a custom message template in the following actions, For beautification, please refer to the beautification article in the follow-up article.

Test script availability

Enter the alarm media type option, find the enterprise wechat applet just created, and click test

Here, the recipient, subject and message can be written freely, and then click test

When the following figure appears, the result is normal

Analog alarm process test

User partial authorization

The path is Admin – > user – > Click Admin user – > alarm media – > Add Select the type as the alarm type media just created, and the recipient can fill it in casually. The activation and alarm level can be filled in according to their own situation.

Find the alarm media, click add, find the enterprise wechat applet in the previous alarm media type, and the recipient can fill it in casually. This step is not done. An error will be reported when an alarm is generated, indicating that there is no user definition, and the alarm sending fails

Create action

Path is configuration – > action – > trigger action – > create action

There are many types of conditions for entering the action, which can be flexibly customized according to their own conditions. This paper takes the host group as the condition.

The operation details are not expanded in detail, and the steps will be expanded in detail in the subsequent alarm upgrade. Based on the user group, this paper only sends it to the enterprise wechat applet as an example. Here you can adjust it according to the actual situation. The notification template has been created in the previous alarm type in the Custom message part, which does not need to be created here, Priority: user defined message in operation details > template in alarm type.

It should be noted here that the template must exist, otherwise the same alarm will fail. If the media is not defined, it is the whole problem.

Analog alarm

Create virtual host

A host that cannot be pinged is built here. Since the previously selected condition is the main unit, it needs to be added to the Zabbix Server host group. It is only for demonstration and can be adjusted according to its own situation. The template is ICMP Ping (under Templates/Modules)

Analog alarm

Due to the inability to ping, wait for a period of time, the front end should appear the alarm of Unavailable by ICMP ping, and there should be corresponding actions. Gray represents normal. If red represents transmission failure, you can analyze the reasons.

effect

If you need to view it on the mobile phone, you need to pay attention to the QR code, otherwise you can only view it in the enterprise wechat.

Write at the end

In fact, the most difficult part of the whole wechat alarm part is the small program part. There are many parameters that need to be adjusted. On the contrary, the way of robot alarm is relatively simple. You only need to call the webhook address of the robot. Later, I will supplement the alarm of wechat robot. Through chatting with some online friends, they still don't understand the meaning of doing so, Of course, there is also the reason why I am not familiar with python. When testing, I have to think about the causes of some problems. Many problems can be found on the Internet. Finally, there is a long way to go. I will ask up and down. I wish you a happy New Year!

Added by tex1820 on Wed, 16 Feb 2022 13:45:10 +0200