Zabbix微信企業訂閱號報警設置

Zabbix微信企業訂閱號報警設置

 

官方提供了較全的api,使用個人訂閱號測試時,發現很多接口沒有權限,無法獲取訂閱者openid,導致無法發送消息,然後要來了公司的企業訂閱號來進行報警。

微信公衆號登錄:https://mp.weixin.qq.com/

微信api參考:http://mp.weixin.qq.com/wiki/16/992df48524118c3e89945856694b30cc.html

微信api在線調試:http://mp.weixin.qq.com/debug/

微信消息發送

1、獲取access_token

官方api文檔:

http://mp.weixin.qq.com/wiki/11/0e4b294685f817b95cbed85ba5e82b8f.html

說明:

    根據應用ID和應用密鑰,獲取access_token,每日獲取token上限2000次,token的有效期爲2小時。

 

2獲取訂閱者openid

官方api文檔:

http://mp.weixin.qq.com/wiki/0/d0e07720fc711c02a3eab6ec33054804.html

說明:

    官方api不能直接根據用戶帳號進行獲取openid,而是通過獲取所有的openid,在遍歷openid找到用戶名,最後得到用戶名與openid的對應關係,然後把接受報警的用戶的openid找到,並記錄。

 

3、發送消息

官方api文檔:

http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html

說明:

    羣發每天限制了4條,只能使用客服接口發送消息,條數上限爲50w

    客服接口限制:當用戶主動發消息給公衆號的時候:(包括髮送信息、點擊自定義菜單、訂閱事件、掃描二維碼事件、支付成功事件、用戶維權),開發者在一段時間內(目前修改爲48小時)可以調用客服消息接口,通過POST一個JSON數據包來發送消息給普通用戶,在48小時內不限制發送次數。所以48小時後,如果用戶沒有再觸發上述事件,報警消息就無法發送。

 

4、微信報警python腳本

#!/usr/bin/env python
#coding=utf-8
#author: yangrong
#date: 2015-8-19
#本微信報警腳本應用於企業訂閱號
#當用戶主動發消息給公衆號的時候(包括髮送信息、點擊自定義菜單、訂閱事件、掃描二維
#碼事件、支付成功事件、用戶維權),微信將會把消息數據推送給開發者,開發者在一段時
#間內(目前修改爲48小時)可以調用客服消息接口,通過POST一個JSON數據包來發送
#消息給普通用戶,在48小時內不限制發送次數。
 
 
 
import os
import urllib2
import requests
import sys
import time
import json
import pickle
 
appid='wxc88**************'     
secret='b9b8925aaa0eafc***********'
token_file='/tmp/token_file.txt'
log_file='/tmp/wechat.log'
openid_user_file='/tmp/openid_user.txt'
openid_list=["omPAFj8PBaE4UbdOGmgjFfq-shFM",   #楊容
            "omPAFj27U-7PJkgYyHMk1wvDI27o",   #阿飛
            ]  #這是微信接收者的openid
 
#報警格式,腳本名  收件人  標題  內容
#這是zabbix發送內容格式,所以
#這裏取出標題和內容就行了
 
#幫助信息,要求必須傳參4個
if len(sys.argv) != 4:
  print 'Usage: %s mail-to title content'%sys.argv[0]
  print 'Example: '
  print '       %[email protected]  "this is testtitle"  "this is test content."'%sys.argv[0]
  sys.exit()
 
title=sys.argv[2]
content=sys.argv[3]
current_hour=time.strftime('%H',time.localtime(time.time()))    
 
 
#日誌記錄函數,把標題,用戶id,狀態記錄
def log(title,openid,status):
         withopen(log_file,'ab') as f:
                   current_time=time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time()))
                   f.write('%s| %s | %s | %s\n'%(current_time,openid,status,title))
 
 
#獲取token
class Token(object):
   def __init__(self, appid, secret):
       self.baseurl ='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}'.format(
           appid,secret)
       self.expire_time = sys.maxint
 
   def get_token(self):
       if self.expire_time > time.time():
           request = urllib2.Request(self.baseurl)
           response = urllib2.urlopen(request)
           ret = response.read().strip()
           ret = json.loads(ret)
           if 'errcode' in ret.keys():
                print >> ret['errmsg'],sys.stderr
                sys.exit(1)
           self.expire_time = time.time() + ret['expires_in']
           self.access_token = ret['access_token']
             token_pre=[current_hour,self.access_token]
             with open(token_file,'wb') as f:
                      pickle.dump(token_pre,f)
       return self.access_token
 
#access_token = Token(appid=appid,secret=secret).get_token()  #這是獲取access_token的代碼
#print access_token
 
 
#獲取所有的openid,然後根據openid獲取用戶信息,提取出用戶名,最後輸出用戶名與openid的對應關係。
class get_user():
         def__init__(self):
                   self.access_token=Token(appid,secret).get_token()
         defget_openid_list(self):
                   openid_list_url='https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid='.format(self.access_token)
                   request=urllib2.Request(openid_list_url)
                   response=urllib2.urlopen(request)
                   ret=response.read().strip()
                   openid_list= json.loads(ret)
                   #printopenid_list['data']['openid']
                   openid_list= openid_list['data']['openid']
                   foropenid in openid_list:
                            user_info_url='https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}'.format(self.access_token,openid)
                            user_info_request=urllib2.Request(user_info_url)
                            user_info_response=urllib2.urlopen(user_info_request).read().strip()
                            user_info=json.loads(user_info_response)
                            if'errcode' in user_info.keys():
                                     print>> user_info['errmsg'],sys.stderr
                                     sys.exit() 
                            withopen(openid_user_file,'wb') as f:
                                     f.write('openid:%s  nickname:%s'%(openid,user_info['nickname']))    
#使用post方式發送報警
def send_msg(title,content):
       #一天能夠獲取的access_token次數是2000次,每次取到的token有效時間2小時,所以pickle dump時,把當前小時數與access_token寫入文件,每一小時獲取一次token.
         current_hour=time.strftime('%H',time.localtime(time.time()))    
         ifnot os.path.exists(token_file):
                   access_token=Token(appid,secret).get_token()
         withopen(token_file,'rb') as f:
                   token_pre=pickle.load(f)
                   #print'token_pre:',token_pre
         access_token_pre=token_pre[1]
         current_hour_pre=token_pre[0]
         ifcurrent_hour == current_hour_pre:
                   access_token=access_token_pre
         else:
                   access_token=Token(appid,secret).get_token()
         #print'access_token:',access_token
       #循環openid_list,給每個成員單獨推送微信消息
         foropenid in openid_list:
                   #print'openid:',openid
                   url='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s'%access_token
                   payload={
                    "touser": '%s'%openid,
                      "msgtype": "text",
                      "text": {
                     "content": "Title: %s\nContent:%s"%(title,content)
                                }
                   }       
                   ret= requests.post(url, data=json.dumps(payload, ensure_ascii=False),verify=False)
                   result=ret.json()
                  
                   #printresult
                   #如果這一次發送失敗,則代表可能access_token有問題,刪除pickle dump文件,重新生成一次access_token
                   if  result['errcode']:
                            log(title,openid,'sendfail')      
                            os.remove(token_file)
                            access_token=Token(appid,secret).get_token()
                   else:
                            log(title,openid,'sendsuccess')      
                           
                   #printpost(url, data)
 
 
#get_user().get_openid_list()   #這是遍歷所有openid,獲取openid和用戶名的對應關係。
 
send_msg(title,content)  #發送微信信息

   

zabbix報警設置

1)把報警腳本放到zabbix報警路徑下,默認是:

    /usr/local/zabbix/share/zabbix/alertscripts

2)web添加報警介質

 

wKiom1XcHTCAlzOYAAEMTBMykkA437.jpg


3)添加報警動作

 wKioL1XcH0bTtq6sAAC2VLMO60Q026.jpg


4)設置用戶報警

 wKiom1XcHTGz_FkPAAEYeBgbspk980.jpg

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章