最近在折腾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[0][-3:] Year = datalist[2] Day = datalist[1] SWtime = datalist[3].split('+')[0] templist = datalist[5].split('/') print 'templist = ',templist Facility = templist[0] Priority = templist[1] ReportTime = Year + '-' + str(Mothlist[Moth]) + '-' + Day +' '+ SWtime RecvTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) FromHost = datalist[4] client_ip = client_addr[0] SysLogTag = templist[2] Message = '' #print datalist for m in range(0,len(datalist)): # print 'm is ',m try:Message = Message + datalist[5+m] 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 '*'*20 db.close()
最后,用后台免登陆执行
nohup sw_logserver.py &