shenzhang 发表于 2019-1-24 13:39:40

Zabbix 微信告警脚本

  使用:
  curl -s -G url 获取 AccessToken
  使用:
  curl --data url 传送凭证调用企业号接口
  zabbix会传递三个参数给脚本,$1是消息接收账号,$2报警标题,$3报警内容
  >>SHELL
  #!/bin/bash
  # Functions: send messages to wechat app
  # set variables
  CropID='your corpid'
  Secret='your corpsecret'
  GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
  #get acccess_token
  Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F\" '{print $4}')
  PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$Gtoken"
  #
  function body() {
  local int AppID=1
  local UserID="test001"
  local PartyID=3
  local Msg=$(echo "$@" | cut -d" " -f3-)
  printf '{\n'
  printf '\t"touser": "'"$UserID"\"",\n"
  printf '\t"toparty": "'"$PartyID"\"",\n"
  printf '\t"msgtype": "text",\n'
  printf '\t"agentid": "'" $AppID "\"",\n"
  printf '\t"text": {\n'
  printf '\t\t"content": "'"$Msg"\""\n"
  printf '\t},\n'
  printf '\t"safe":"0"\n'
  printf '}\n'
  }
  /usr/bin/curl --data-ascii "$(body $! $2 $3)" $PURL
  注意:
  上面脚本中标注的几处:
  CorpID和Secret分别是上面企业公众号的管理组monit-manager的ID
  UseID:用户账号。这里只需要填写一个账号即可。zabbix的web界面里发信是按照应用ID,只要关注这个微信企业号内的用户都会收到报警邮件。
  AppID:应用ID
  PartyID:部门ID号
  >>PYTHON
  #!/usr/bin/python
  #_*_coding:utf-8 _*_
  import urllib,urllib2
  import json
  import sys
  import simplejson
  reload(sys)
  sys.setdefaultencoding('utf-8')
  def gettoken(corpid,corpsecret):
  gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
  printgettoken_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":"test001",
  "toparty":"3",
  "msgtype":"text",
  "agentid":"1",
  "text":{
  "content":subject + '\n' + content
  },
  "safe":"0"
  }
  #    send_data = json.dumps(send_values, ensure_ascii=False)
  send_data = simplejson.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)
  subject = str(sys.argv)
  content = str(sys.argv)
  corpid ='your corpid'
  corpsecret = 'your corpsecret'
  accesstoken = gettoken(corpid,corpsecret)
  senddata(accesstoken,user,subject,content)
  上面脚本中涉及了微信企业号中的用户(任意一个即可,如上的test001),应用ID,部门ID,corpid和secret

页: [1]
查看完整版本: Zabbix 微信告警脚本