其他
Python脚本实现Zabbix自动微信告警
先放个链接,万一有人关注呢
优质文章推荐
↓ ↓ ↓ ↓ ↓
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib,urllib2,json
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
class WeChat(object):
__token_id = ''
# init attribute
def __init__(self,url):
self.__url = url.rstrip('/')
self.__corpid = 'wwa565a55049873ca6'
self.__secret = 'OKVyP9Xo-WwnnzZXYbMla9SONypikYwGV-X0lqZ1kUA'
# Get TokenID
def authID(self):
params = {'corpid':self.__corpid, 'corpsecret':self.__secret}
data = urllib.urlencode(params)
content = self.getToken(data)
try:
self.__token_id = content['access_token']
# print content['access_token']
except KeyError:
raise KeyError
# Establish a connection
def getToken(self,data,url_prefix='/'):
url = self.__url + url_prefix + 'gettoken?'
try:
response = urllib2.Request(url + data)
except KeyError:
raise KeyError
result = urllib2.urlopen(response)
content = json.loads(result.read())
return content
# Get sendmessage url
def postData(self,data,url_prefix='/'):
url = self.__url + url_prefix + 'message/send?access_token=%s' % self.__token_id
request = urllib2.Request(url,data)
try:
result = urllib2.urlopen(request)
except urllib2.HTTPError as e:
if hasattr(e,'reason'):
print 'reason',e.reason
elif hasattr(e,'code'):
print 'code',e.code
return 0
else:
content = json.loads(result.read())
result.close()
return content
# send message
def sendMessage(self,touser,message):
self.authID()
data = json.dumps({
'touser':touser,
'toparty':1,
'msgtype':"text",
'agentid':"1000002",
'text':{
'content':message
},
'safe':"0"
},ensure_ascii=False)
response = self.postData(data)
print response
if __name__ == '__main__':
a = WeChat('https://qyapi.weixin.qq.com/cgi-bin')
a.sendMessage(sys.argv[1],sys.argv[3])
上述示例中需要注意的是,有4处内容需要用户按照实际信息进行填写。其中,self.__corpid的参数值需要填写企业ID,self.__secret的参数值需要填写应用的secret信息,toparty的参数值需要填写部门ID,agentid的参数值需要填写应用的agentid信息。
脚本配置完成之后,需要为脚本文件授予权限才能执行。
来不及解释了,快上车!(进群看公告)
欢迎新的小伙伴加入!在这里,我们鼓励大家积极参与群内讨论和交流,分享自己的见解和经验,一起学习和成长。同时,也欢迎大家提出问题和建议,让我们不断改进和完善这个平台。
↓↓↓ 点个在看,无需赞赏!