#!/usr/bin/python # -*- coding=utf-8 -*- #from get_ip_netifaces import get_ip_address import sys import json import httplib,urllib import time import datetime import os.path import uuid import json from socket import * import fcntl import struct #CAHost及应用秘钥 CAHost = "api.aiops.com" appID = "10c33ca227c54f1ba9555a5ca03a8e66" conn = httplib.HTTPConnection(CAHost, 80, timeout=10) def send_webhook(tag,host,message,priority,procid,facility,programName): params = {"app":appID,"tag":tag,"host":host,"message":message,"priority":priority,"procid":procid,"facility":facility,"programName":programName} print(str(datetime.datetime.now()).split('.')[0] + " " + json.dumps(params,ensure_ascii=False)) headers = {"Content-type": "application/json","User-Agent": "syslog"} conn.request("POST", "http://" + CAHost + "/alert/api/event/syslog/" + appID, json.dumps(params, ensure_ascii=False), headers) response = conn.getresponse() print(str(datetime.datetime.now()).split('.')[0] + " " + str(response.status) + " " + str(response.read())) def get_host_ip(): try: s=socket(AF_INET,SOCK_DGRAM) s.connect(('8.8.8.8',80)) ip=s.getsockname()[0] finally: s.close() return ip def rsyslog_receiver(protocol, port=8515): # 创建rsyslog_receiver服务器,监听syslog发送来的信息 #if_ip = get_ip_address(ifname) ipv4Addr = ('0.0.0.0', port) ipv6Addr = ('::1', port) bufsize = 1024 print("Rsyslog Receiver Started!!!") try: if 'ipv4' == protocol: udpServer = socket(AF_INET, SOCK_DGRAM) udpServer.bind(ipv4Addr) elif 'ipv6' == protocol: udpServer = socket(AF_INET6, SOCK_DGRAM) udpServer.bind(ipv6Addr) print("Waiting for connection....") while True: data, xxx = udpServer.recvfrom(bufsize) data = data.decode(encoding='utf-8') dataJson = json.loads(data) print(data) print("programName: ", dataJson["programName"]) print("nowtime:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) host = get_host_ip() programName = dataJson["programName"] facility = dataJson["facility"] procid = dataJson["procid"] priority = dataJson["priority"] message = dataJson["message"] tag = dataJson["tag"] send_webhook(tag,host,message,priority,procid,facility,programName) except Exception: os.system('kill -9 `ps aux | grep rsyslog_monitor.py | grep -v \"grep\" | awk \'{print $2}\'` && nohup sudo python -u /aiops/local/syslog/rsyslog_monitor.py >> /aiops/local/syslog/rsyslog.log 2>&1 &') rsyslog_receiver() raise if __name__ == "__main__": # 使用Linux解释器 & WIN解释器 rsyslog_receiver('ipv4') rsyslog_receiver('ipv6')