Splunk對接企業微信自定義SPL命令

簡介

新版8.0.3使用微信告警APP有問題(需要以英文打開splunk前端纔會沒問題),舊告警腳本功能被廢除(已被自定義告警代替),所以做個自定義命令來使用。方便靈活。

環境

  1. Centos7
  2. Splunk 8.0.3
  3. Python2.7
  4. SDK 1.6.13

代碼

# coding: utf-8
# 20200621 by 
#

import sys
import urllib3
import requests
import time
from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option, validators
from splunklib import six
import logging
import json
log_filename = "/opt/splunk/var/log/splunk/wechat_message.log"
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

@Configuration()
class WechatMessage(StreamingCommand):

    corpid  = Option(require=True, validate=validators.Fieldname())
    secret  = Option(require=True, validate=validators.Fieldname())
    tagid   = Option(require=True, validate=validators.Fieldname())
    partyid = Option(require=True, validate=validators.Fieldname())
    agentid = Option(require=True, validate=validators.Fieldname())
    user    = Option(require=True, validate=validators.Fieldname())

    title   = Option(require=True, validate=validators.Fieldname())
    content = Option(require=True, validate=validators.Fieldname())
    
    def __get_token(self, record):
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        params = {
            "corpid": record[self.corpid],
            "corpsecret": record[self.secret],
        }
        r = requests.get(url = url, params = params, verify = False)
        if r.json()['errcode'] != 0:
            return False
        else:
            token = r.json()['access_token']
            return token

    def __send_message(self, record):
        token = self.__get_token(record)
        if token == False:
            return "Corpid or Secret invalid"
        
        base_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
        url = base_url + token
        data = {
            "touser": record[self.user],
            "totag": record[self.tagid],
            "toparty": record[self.partyid],
            "msgtype": "text",
            "agentid": record[self.agentid],
            "text": {
                "content": record[self.title] + '\n' + record[self.content]
            },
            "safe": "0"
        }
        r = requests.post(url = url, data = json.dumps(data), verify = False)
        while r.json()['errcode'] != 0 and n < 4:
            n += 1
            token = self.__get_token(record)
            if token == False:
                return "Corpid or Secret invalid"
            url = base_url + token
            r = requests.post(url = url, data = json.dumps(data), verify = False)

        return "Success"

    def __log_to_file(self, filename):
        self.logger.setLevel(level=logging.INFO)
        handler = logging.FileHandler(filename)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    def stream(self, records):
        self.__log_to_file(log_filename)
        for record in records:
            status = self.__send_message(record)
            self.logger.info("CorpID: " + record[self.corpid])
            self.logger.info("Title: " + record[self.title])
            self.logger.info("Content: " + record[self.content])
            self.logger.info("Status: " + status)
            record["status"] = status
            yield record

dispatch(WechatMessage, sys.argv, sys.stdin, sys.stdout, __name__)

# test spl

# | makeresults
# | eval 
#   corpid  = "wwcc4366cc",
#   secret  = "mXr0eu2oLYaOf_ZJMIx5liI",
#   tagid   = "1",
#   partyid = "1",
#   agentid = "1000002",
#   user    = "testuser",
#   title   = "test",
#   content = "qwerqewr"
# | sendwechat corpid=corpid secret=secret tagid=tagid partyid=partyid agentid=agentid user=user title=title content=content


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