最近在折騰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 + ` `) #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 &