由於不會編寫graylog的插件,我們通過python腳本來間接實現釘釘告警.
我們可以在代碼里實現我們想要的任何支持的告警方式,也可以在邏輯里增加對告警內容的二次處理再通知.
更多內容請查看博客地址:https://www.jonnyan404.top:8088/
代碼內容如下:
點擊查看詳細內容
# coding:utf-8 # python3.6 # 只支持HTTP頭包含Content-Length的請求 # @創建者:jonnyan404 # #日期:2020-05-09 # 博客地址:www.jonnyan404.top:8088
import socket
import threading
import json
import my_logging
import logging
import requestsmy_logging.load_my_logging_cfg()
HTTPHEADER = b"""HTTP/1.1 200 OK
Content-Type: text/html;charset=utf-8
Connection:Keep-Alive"""
def resolve_http_header(header):
header = header.decode('utf-8')
headers = {}
for i in header.split('\r\n'):
if ':' in i:
k = i.split('😂[0].strip()
v = i.split('😂[1].strip()
headers[k] = v
return headersdef dingding(text):
headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = "此處更改為你自己的釘釘api url"
json_text= {
"msgtype": "text",
"at": {
"atMobiles": [
"你的手機號碼"
],
"isAtAll": False
},
"text": {
"content": text
}
}
requests.post(api_url,json.dumps(json_text),headers=headers).contentclass React(threading.Thread):
def init(self, conn, addr):
threading.Thread.init(self)
self.setDaemon(True)
self.conn = conn
self.addr = addrdef read_chunk(self): data = b'' # 第一次接收 try: self.conn.settimeout(5) chunk = self.conn.recv(1024) except Exception as e: logging.error(e) return b'', b'' header_len = chunk.index(b'\r\n\r\n') + len(b'\r\n\r\n') # 獲取請求頭並轉換成字典格式 header = chunk[:header_len] headers = resolve_http_header(header) # 將第一次請求獲取到的數據部分保存到data data += chunk[header_len:] data = data.strip() if data else b'' # print(header) # print() # print(data) # 在while循環中接收剩余數據,當data長度與header中的Content-Length相同時結束循環 try: print('Contetn-Length:', headers['Content-Length']) logging.info('Contetn-Length:', headers['Content-Length']) except: print('http header error.') logging.error('http header error.') return b'', b'' while not int(headers['Content-Length']) == len(data): try: chunk = self.conn.recv(4096) if chunk: data += chunk logging.info('read %d bytes.' % len(data)) # 如果客戶端沒有主動關閉連接則不再接收 else: break except Exception as e: logging.error(e) break logging.info('done') # 數據接收完成,響應客戶端請求,並關閉連接 self.conn.send(HTTPHEADER + b'ok ') self.conn.close() return header, data def run(self): header, payload = self.read_chunk() if not header or not payload: return # 保存接收到的所有數據 logging.info(payload) data=json.loads(payload.decode("utf-8")) msg=data['event']['message'] logging.info(msg) dingding(msg)
def server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
address = ('0.0.0.0', 8000)
s.bind(address)s.listen(5) logging.info('listening on port %d ...' % 8000) while True: conn, addr = s.accept() React(conn, addr).start()
if name == 'main':
server()
注意:代碼里的 my_logging 文件為我自己的日志配置文件,請注意自行更換或去除.
- 運行上方的代碼
- 在告警配置處,填寫http://ip:port