Python

Log File -> Cfg File -> CSV File (fortigate 방화벽 정책 한정)

Ao1 2022. 8. 31. 15:40

Log_Change_Cfg.py
0.00MB

@fgpoliciestocsv.py 파일 필요

 

import os
import argparse
import subprocess

parser = argparse.ArgumentParser(description='Log File -> Cfg File')
parser.add_argument('-p', metavar='[File_path]', required=True, help='File path', type=str)
args = parser.parse_args()

path = args.p                                       # 디렉토리 경로
s_ch = os.listdir(path)                             # 디렉토리 내 파일 리스트                                                        
c_ch = []                                           # .log 확장자 파일 리스트
f_name_arg = []                                     # 파일 이름 리스트

PATH_DIR = './CFG'

# 디렉토리 생성
def createDir(DIR):
    if not os.path.exists(DIR):
        os.makedirs(DIR)

createDir(PATH_DIR)

for i in range(0,len(s_ch)):
    f_name, f_ext = os.path.splitext(s_ch[i])       # 파일 이름과 확장자 분리

    if f_ext == '.log':                             # .log 확장자 파일 분리
        c_ch.append(s_ch[i])
        f_name_arg.append(f_name)


for x in range(0,len(c_ch)):
    cut_count = 0                                       # 컷팅 카운터
    one_count = []                                      # 첫번째 컷팅 카운터 저장
    two_count = []                                      # 마지막 컷팅 카운터 저장

    with open(path + '/' + c_ch[x], 'r', encoding='utf-8') as file:
        count = 0
        data = file.readlines()
        for line in data:
            count += 1
            if 'config firewall policy' in line:
                one_count.append(count)

    with open(path + '/' + f_name_arg[x] + '.log', 'w', encoding='utf-8') as file:
        count = 0
        file.seek(0)
        for line in data:
            file.write('')
            count += 1
            if int(one_count[0]) -1 < count:
                file.write(line)

    with open(path + '/' + c_ch[x], 'r', encoding='utf-8') as file:
        count = 0 
        data = file.readlines()
        for line in data:
            count += 1
            if 'config' in line:
                two_count.append(count)

    with open(PATH_DIR + '/' + f_name_arg[x] + '.cfg', 'w', encoding='utf-8') as file:
        count = 0
        file.seek(0)
        for line in data:
            count += 1
            if int(two_count[1]) > count:
                file.write(line)
            else:
                file.truncate()

PATH_DIR_csv = './CSV'
createDir(PATH_DIR_csv)

for n in range(0,len(c_ch)):
    subprocess.call('fgpoliciestocsv.py -i ' + PATH_DIR + '/' + f_name_arg[n] + '.cfg ' + '-o ' + PATH_DIR_csv + '/' + f_name_arg[n] + '.csv', shell=True)