#-*-coding:utf-8-*-
"""
功能:解析日志入库
"""
import os,sys,time,re
import MySQLdb
regex= "(\|\d+\.\d+\.\d+\.\d+:\d+|\d+\.\d+\.\d+\.\d+|\d+-\w.*from)"
p = re.compile(regex)
conn = MySQLdb.connect("localhost","root","123","syslog",port=3306,connect_timeout=10,compress=True,charset='utf8',use_unicode=True)
cursor=conn.cursor()
path = os.path.abspath(os.path.dirname(sys.argv[0]))
tmplog = time.strftime("%Y%m%d", time.localtime())
currhour = time.strftime("%d", time.localtime())
fullpath = path + os.sep + tmplog
file_object = open(fullpath + os.sep + currhour + '.txt', 'r')
for current_line_number,line in enumerate(file_object):
results = p.findall(line)
try:
pppoe = results[0].replace("<","").replace(">","").replace("pppoe-","").strip()
sip = results[1].strip()
vip = results[2].strip()
months = results[3].replace("from","").split("-")[1].split(" ")[0]
days = results[3].replace("from","").split("-")[0]
times = results[3].replace("from","").split("-")[1].split(" ")[1]
routeip = results[4]
except Exception,e:
pppoe = ''
sip = results[0].strip()
vip = results[1].strip()
months = results[2].replace("from","").split("-")[1].split(" ")[0]
days = results[2].replace("from","").split("-")[0]
times = results[2].replace("from","").split("-")[1].split(" ")[1]
routeip = results[3]
sql = "insert into syslog(pppoe,sip,vip,months,days,times,routeip) values('%s','%s','%s','%s','%s','%s','%s')"%(pppoe,sip,vip,months,days,times,routeip)
cursor.execute(sql)
conn.commit()
cursor = None
conn.close()
conn = None
|