import json
import requests
import time
import hmac
import hashlib
import base64
import urllib.parse
from urllib.parse import urlparse
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def send():
if request.method == 'POST':
post_data = request.get_data()
app.logger.debug(post_data)
send_alert(json.loads(post_data))
return 'success'
else:
return 'weclome to use prometheus alertmanager dingtalk webhook server!'
def send_alert(data):
token = 'xx'
secret = 'xx'
timestamp = int(round(time.time() * 1000))
url = 'https://oapi.dingtalk.com/robot/send?access_token=%s×tamp=%d&sign=%s' % (token, timestamp, make_sign(timestamp, secret))
alerts = data['alerts']
alert_name = alerts[0]['labels']['alertname']
data_count = []
for k in alerts:
a= k['labels']['job']
b = k['labels']['instance']
c = k['annotations']['description']
data_count.append('\n' + '--------------------------' + '\n' + "名称: " + a + '\n' +'主机IP:' + b + '\n' + '内容:' + c)
data_count = "\n".join(data_count)
title = '%s 有 %d 条新的报警' % (alert_name, len(alerts))
send_data = {
"msgtype": "markdown",
"markdown": {
"title": title,
"text": title + "\n" + "![](https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/prometheus-recording-rules.png)\n" + data_count
}
}
req = requests.post(url, json=send_data)
def make_sign(timestamp, secret):
secret_enc = bytes(secret, 'utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = bytes(string_to_sign, '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))
return sign
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
【无标题】prometheus 钉钉webhook,加签方式
于 2022-05-10 18:51:55 首次发布