江南才子 发表于 2021-6-23 21:58:14

linux下用python写的一个syslog服务进程脚本

  最近在折腾rsyslog+loganalyzer+mysql,搭建OK,无奈rsyslogd识别华为交换机输出日志的格式有点偏差,只能自己在rsyslog服务器上重新写一个进程,用来接收华为交换机的info-center,并写入数据库里,代码如下(基本没做错误检测机制)#!/usr/bin/python
import MySQLdb,time,datetime
from socket import *
host = '172.16.0.45'
port = 514
addr = (host,port)
s = socket(AF_INET,SOCK_DGRAM)
s.bind(addr)
db = MySQLdb.connect('172.16.0.45','rsyslog','p@ssw0rd','Syslog')
cursor = db.cursor()
cursor.execute('select version()')
data = cursor.fetchone()
print 'data ver is ', data
Mothlist = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12}
while 1:

      client_data,client_addr = s.recvfrom(8092)
      print 'got connection from ',client_addr
      if '172.16.201.' not in str(client_addr):
            print 'can not connect from except 172.16.201.0/24',str(client_addr)
            continue
      #file = open('log.txt','a')
      #file.write(client_data + '\n')
      #file.close()
      datalist = client_data.split(' ')
      print 'datalist = ',datalist
      Moth = datalist[-3:]
      Year = datalist
      Day = datalist
      SWtime = datalist.split('+')

      templist = datalist.split('/')
      print 'templist = ',templist
      Facility = templist
      Priority = templist
      ReportTime =Year +'-' + str(Mothlist) + '-' + Day +' '+ SWtime
      RecvTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
      FromHost = datalist
      client_ip = client_addr
      SysLogTag = templist
      Message = ''
      #print datalist
      for m in range(0,len(datalist)):
print 'm is ',m


                try:Message = Message + datalist
                except:pass
print 'msg is', Message


      sql = "INSERT INTO SystemEvents(Priority,ReceivedAt,DeviceReportedTime, FromHost, FromIP,SysLogTag, Message) VALUES ('%s', '%s', '%s','%s','%s','%s','%s')" %(Priority,RecvTime,ReportTime,FromHost,client_ip,SysLogTag,Message)
sql = """INSERT INTO SystemEvents(ReceivedAt,DeviceReportedTime, FromHost, FromIP, Message) VALUES ('2015-08-08 8:8:8', '2018-9-9 9:9:9', 'host test', '2.2.2.2', 'messssss')"""


      #print 'sql is :',sql
      cursor.execute(sql)
      db.commit()
      #print '*'*20db.close()
最后,用后台免登陆执行nohup sw_logserver.py &

页: [1]
查看完整版本: linux下用python写的一个syslog服务进程脚本