본문 바로가기
[ ★ ]Study/Programming

[Python] 방화벽 로그 DB삽입

by nroses-taek 2020. 12. 8.

너무 대충 짠 코드

import pymysql
import ipaddress
from datetime import datetime
import time
import re

conn = pymysql.connect(host='localhost', user='userID', password='1234', db='DB', charset='utf8')
curs = conn.cursor()
sql = "insert into firewall(date, fwrule, src_ip, src_mac, src_port, dst_ip, dst_port)\
    values (%s, %s, %s, %s, %s, %s ,%s)"

logfile_path = '로그파일경로'
logfile_fullpath = logfile_path + 'BoB_DF_firewall.log'
#logfile_fullpath = logfile_path + 'firewall.log'
count = 0
count2 = 0
db_list = []
with open(logfile_fullpath, 'r') as f:
    for line in f:
        if len(line) < 10:
            continue
        count += 1
        #division
        #if count < 13000000: continue

        line = line.replace('\x00', '')
        
        log_parse = line.split(' ')

        date = log_parse[0] + " " + log_parse[1]
        epoch_time = time.mktime(datetime.strptime(date, '%Y-%m-%d %H:%M:%S').timetuple())
        epoch_time = int(epoch_time)
        # epoch -> date
        #date = datetime.fromtimestamp(int(epoch_time)).strftime('%Y-%m-%d %H:%M:%S')
        
        fwrule = int(log_parse[7].split('=')[1])
        re_src_ip = re.sub('[-=+,#/\?:^$@*\"\\‘|\(\)\[\]]', '', log_parse[9].split('=')[1])
        
        #if count == 1041: print(re_src_ip)
        
        src_ip = int(ipaddress.IPv4Address(re_src_ip))
        re_src_mac = re.sub('[-=+,#/\?:^$@*\"\\‘|\(\)\[\]]', '', log_parse[10].split('=')[1])
        src_mac = re_src_mac
        
        #str_mac -> int_mac -> str_mac
        mac_test = src_mac.replace(':','')
        int_mac = int(mac_test,16)
        '''
        byte_mac = bytearray.fromhex('{:012X}'.format(int_mac))
        mac_test_str = ':'.join('{:02X}'.format(byte_mac[i]) for i in range(0,6))
        '''
        src_port = int(log_parse[11].split('=')[1])
        dst_ip = int(ipaddress.IPv4Address(log_parse[12].split('=')[1]))
        dst_port = int(log_parse[13].split('=')[1])

        # for executemany
        db_list.append([])
        db_list[count-1].append(epoch_time)
        db_list[count-1].append(fwrule)
        db_list[count-1].append(src_ip)
        db_list[count-1].append(int_mac)
        db_list[count-1].append(src_port)
        db_list[count-1].append(dst_ip)
        db_list[count-1].append(dst_port)
        
        if count % 1000000 == 0:
            count2 += 1
            print(count2)
            curs.executemany(sql, db_list)
            conn.commit()
#            print(count)
            db_list = []
            count = 0
            
conn.close()
f.close()

if count % 100000 == 0:
의 목적은 python list 수의 한계가 있기 때문에 중간중간 DB에 넣어주는 작업.

중간중간 주석된 부부은 역 변환 코드이니 참고하면 될 듯 하다.

해당 코드 대상의 로그 형식은 아래와 같다. ( 띄어쓰기 기준 )

1 필드 : 날짜
2 필드 : 시간
3 필드 : severity=info
4 필드 : sys=SecureNet
5 필드 : sub=Packetfilter
6 필드 : name=Packet
7 필드 : action=Passed
8 필드 : fwrule=숫자
9 필드 : src_id
10 필드 : src_ip
11필드 : src_mac
12필드 : src_port
13필드 : dst_ip
14필드 : dst_port
15필드 : length

댓글