钉钉报警方式
git clone https://github.com/xuyaoqiang/elastalert-dingtalk-plugin.git
cp -rvf elastalert-dingtalk-plugin/elastalert_modules/ .
由于这个不支持加签的方式通知,修改一下代码.(如果钉钉设置了加签不想关的话就可以改,没有设置加签的就不用管)
修改代码如下
vim elastalert_modules/dingtalk_alert.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
import requests
from elastalert.alerts import Alerter, DateTimeEncoder
from requests.exceptions import RequestException
from elastalert.util import EAException
import time
import hmac
import hashlib
import base64
import urllib.parse
class DingTalkAlerter(Alerter):
required_options = frozenset(['dingtalk_webhook', 'dingtalk_msgtype'])
def __init__(self, rule):
super(DingTalkAlerter, self).__init__(rule)
self.dingtalk_webhook_url = self.rule['dingtalk_webhook']
self.dingtalk_msgtype = self.rule.get('dingtalk_msgtype', 'text')
self.dingtalk_isAtAll = self.rule.get('dingtalk_isAtAll', False)
self.dingtalk_title = self.rule.get('dingtalk_title', '')
self.dingtalk_secret = self.rule.get('dingtalk_secret','')
def format_body(self, body):
return body.encode('utf8')
def alert(self, matches):
headers = {
"Content-Type": "application/json",
"Accept": "application/json;charset=utf-8"
}
body = self.create_alert_body(matches)
payload = {
"msgtype": self.dingtalk_msgtype,
"text": {
"content": body
},
"at": {
"isAtAll": False
}
}
if self.dingtalk_secret!="":
timestamp = str(round(time.time() * 1000))
secret = self.dingtalk_secret
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
self.dingtalk_webhook_url=self.dingtalk_webhook_url+"×tamp={}&sign={}".format(timestamp,sign)
try:
response = requests.post(self.dingtalk_webhook_url,
data=json.dumps(payload, cls=DateTimeEncoder),
headers=headers)
response.raise_for_status()
except RequestException as e:
raise EAException("Error request to Dingtalk: {0}".format(str(e)))
def get_info(self):
return {
"type": "dingtalk",
"dingtalk_webhook": self.dingtalk_webhook_url
}
pass
添加报警方式
alert:
- "elastalert_modules.dingtalk_alert.DingTalkAlerter"
dingtalk_webhook: "https://oapi.dingtalk.com/robot/send?access_token=91545e3c8147f*******839cd8ff4d637bc0ff0fa4d44b852"
dingtalk_msgtype: text
dingtalk_secret: "SEC0637*******edbf3a" #没设置加签不用写