73 lines
2.6 KiB
Python
73 lines
2.6 KiB
Python
import re
|
|
import os
|
|
import time
|
|
|
|
CHUNK_SIZE = 5
|
|
|
|
def read_lookup_table(lookup_table_path):
|
|
"""
|
|
para ler a tabela de pesquisa e retornar um dicionário mapeando endereços IP para nomes de usuário.
|
|
"""
|
|
ip_to_username = {}
|
|
with open(lookup_table_path, 'r') as lookup_file:
|
|
for line in lookup_file:
|
|
parts = line.strip().split()
|
|
if len(parts) == 2:
|
|
ip, username = parts
|
|
ip_to_username[ip] = username
|
|
else:
|
|
print(f"Skipping line in lookup table: {line.strip()}")
|
|
return ip_to_username
|
|
|
|
|
|
def process_chunk(chunk, lookup_table_path):
|
|
"""
|
|
Processa um pedaço de linhas do arquivo de log.
|
|
|
|
"""
|
|
ip_to_username = read_lookup_table(lookup_table_path)
|
|
modified_lines = []
|
|
for line in chunk:
|
|
modified_line = line
|
|
match = re.search(r"\s+-\s+(\d+\.\d+\.\d+\.\d+)", modified_line)
|
|
if match:
|
|
ip_address = match.group(1).strip()
|
|
if ip_address in ip_to_username:
|
|
username = ip_to_username[ip_address]
|
|
modified_line = re.sub(r"\s+-\s+(\d+\.\d+\.\d+\.\d+)", f" {username:<15} {ip_address}", modified_line)
|
|
modified_lines.append(modified_line)
|
|
return modified_lines
|
|
|
|
class LogTracker:
|
|
def __init__(self, input_log_path, output_log_path, lookup_table_path):
|
|
self.input_log_path = input_log_path
|
|
self.output_log_path = output_log_path
|
|
self.lookup_table_path = lookup_table_path
|
|
self.last_position = 0
|
|
|
|
def track_log(self):
|
|
while True:
|
|
with open(self.input_log_path, 'r') as infile:
|
|
infile.seek(self.last_position)
|
|
lines = infile.readlines()
|
|
self.last_position = infile.tell()
|
|
|
|
chunks = [lines[i:i + CHUNK_SIZE] for i in range(0, len(lines), CHUNK_SIZE)]
|
|
for chunk in chunks:
|
|
modified_lines = process_chunk(chunk, self.lookup_table_path)
|
|
with open(self.output_log_path, 'a') as outfile:
|
|
outfile.writelines(modified_lines)
|
|
|
|
# Sleep for a while before reading the log file again
|
|
time.sleep(1)
|
|
|
|
|
|
def modify_logfile_continuously(input_log_path, output_log_path, lookup_table_path):
|
|
log_tracker = LogTracker(input_log_path, output_log_path, lookup_table_path)
|
|
log_tracker.track_log()
|
|
|
|
if __name__ == "__main__":
|
|
input_log_path = "logger.log"
|
|
output_log_path = "log_modified.log"
|
|
lookup_table_path = "lookup_table.tsv"
|
|
modify_logfile_continuously(input_log_path, output_log_path, lookup_table_path) |