Home Backend Development Python Tutorial Zabbix implements WeChat alarm function

Zabbix implements WeChat alarm function

Dec 05, 2016 pm 01:27 PM

1. Apply for a corporate WeChat account, application address https://qy.weixin.qq.com/


2. Log in to the corporate WeChat account

Picture 1

Picture 2

2. Add WeChat account

Picture 1

Picture 2

After completing the above steps, you have completed adding the WeChat account

3. Create a new application

Picture 1

Picture 2

Picture 3

Picture 4

After the above four pictures are completed, the application creation is completed

4. Set permission management

Picture 1

Picture 2

Picture 3

After completing the operations of the above three pictures, the permission management settings are completed; now the WeChat settings are completed!

5. Zabbix Server configuration

Picture 1

Picture 2

Picture 3

Complete the configuration in the above three pictures, then the configuration of zabbix server has been completed.

7. Weixin.py program content

#!/usr/bin/env python
# encoding: utf-8
# Create time 2016-10-08
#Auth chenpeng
import urllib2
import json
import sys
import time
class WebChat(object):
def __init__(self,CropID,Secret):
self.CropID = CropID
self.Secret = Secret
def Get_Token(self,info):
'''
:param info: 存储执行结果和执行程序状态码code (0代表执行成功,非零表示不成功)
:return:
'''
self.info = info
gurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (self.CropID,self.Secret)
try:
#通过Get方式获取token
req = urllib2.Request(gurl)
response = urllib2.urlopen(req)
g_result = json.loads(response.read(),"UTF-8")
if g_result .has_key('access_token'):
self.info['result']= g_result ['access_token']
self.info['code'] = 0
else:
self.info['result'] = g_result
self.info['code'] = 1
except Exception,e:
self.info['code'] = 1
self.info['result'] = e
def Send_Msg(self,touser,toparty,agentid,access_token,content,info,*args,**kwargs):
'''
发送信息到微信
:param touser: 部门成员id,zabbix中定义的微信接收者,
成员ID列表(消息接收者,多个接收者用‘|'分隔,最多支持1000个)。
特殊情况:指定为@all,则向关注该企业应用的全部成员发送
:param toparty: 部门id,定义了范围,组内成员都可接收到消息,
部门ID列表,多个接收者用‘|'分隔,最多支持100个。当touser为@all时忽略本参数
:param agentid: 企业应用的id,整型。可在应用的设置页面查看
:param access_token: 根据CropID,Secret获取的访问token值
:param content: 滤出zabbix传递的第三个参数,
表示发送微信消息的内容消息内容,最长不超过2048个字节,
注意:主页型应用推送的文本消息在微信端最多只显示20个字(包含中英文)
:param info: 返回执行结果信息{'result':None,'code':None};'code':0或者非零 ;0表示成功 非零表示失败
:param args:
:param kwargs:
:return:
'''
self.touser = touser
self.toparty = toparty
self.agentid = agentid
self.conntent = content
self.access_token = access_token
self.info = info
purl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % (access_token)
data = {
"touser": "",
"toparty": "",
"totag": "", #标签ID列表,多个接收者用‘|'分隔,最多支持100个。当touser为@all时忽略本参数,非必须
"msgtype": "text", #必须
"agentid": "", #必须
"text": {
"content": "" #必须
},
"safe": "0" # 表示是否是保密消息,0表示否,1表示是,默认0
}
data['touser'] = self.touser
data['agentid'] = self.agentid
data['toparty'] = self.toparty
data['text']['content']=self.conntent
data = json.dumps(data,ensure_ascii=False)
try:
#通过PUT方式获取发送数据
req = urllib2.Request(purl, data)
response = urllib2.urlopen(req)
res = json.loads(response.read())
self.info['code'] = res['errcode']
self.info['result'] = res['errmsg']
except Exception,e:
self.info['result'] = e
self.info['code'] = 1
if __name__ == '__main__':
reload(sys)
sys.setdefaultencoding('utf-8')
def log(date, touser, content,info):
'''
发送的日志打印日志
:param date: 时间
:param touser: 发送给谁
:param content: 发送的信息内容
:param info: 发送执行的结果
:return:
'''
msg = '%s %s %s 发送结果 - %s\n' % (date, touser, content, info)
with open('msg.log', 'a') as f:
f.write(msg)
agentid = sys.argv[1]
#agentid = 1
touser = 'xxxxxxx@qq.com'
toparty = ''
content = sys.argv[2:]
content = '\n'.join(content)
#content = '测试'
CropID = 'xxxxxxxxxxxxxxxxxxx'
Secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
info={'result':None,'code':None}
date = time.strftime('%Y-%m-%d %H:%M:%S')
res=WebChat(CropID,Secret)
res.Get_Token(info)
if info['code'] == 0:
access_token = info['result']
res.Send_Msg(touser=touser, toparty=toparty, agentid=agentid, access_token=access_token,
content=content,info=info)
if info['code'] == 0:
content = eval(content)
log(date, touser, content,info)
else:
log(date, touser, content, info)
else:
log(date,touser,content,info)
Copy after login

The CropID and Secret in lines 114 and 115 of the code correspond to the CropID and Secret corresponding to Figure 3 in the fourth step "Set Permission Management"

For the data in line 63 of the code, please refer to the WeChat interface document

Address: http://qydev.weixin.qq.com/wiki/index.php?title=%E5%8F%91%E9%80%81%E6%8E%A5%E5%8F%A3%E8% AF%B4%E6%98%8E

The above is the Zabbix implementation of WeChat alarm function introduced by the editor. I hope it will be helpful to you. 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 your support of the Script House website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles