python实现微信hook_graylog通过python实现钉钉/微信/webhook告警

# 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 requests

my_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 headers

def 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).content

class React(threading.Thread):

def init(self, conn, addr):

threading.Thread.init(self)

self.setDaemon(True)

self.conn = conn

self.addr = addr

def 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()

你可能感兴趣的:(python实现微信hook)