import subprocess
import re
import collections
import time
# Configurações
log_file = '/var/log/syslog'
threshold = 4
block_duration = 86400 # 24 horas em segundos
ip_count = collections.defaultdict(int)
blocked_ips = set()
# Função para bloquear IP
def block_ip(ip):
subprocess.run(['sudo', 'csf', '-d', ip])
# Função para desbloquear IP
def unblock_ip(ip):
subprocess.run(['sudo', 'csf', '-dr', ip])
# Monitorar o log
with open(log_file, 'r') as f:
lines = f.readlines()
for line in lines:
match = re.search(r'SRC=(\d+\.\d+\.\d+\.\d+).*DPT=(\d+)', line)
if match:
ip = match.group(1)
port = match.group(2)
ip_count[ip] += 1
if ip_count[ip] >= threshold and ip not in blocked_ips:
block_ip(ip)
blocked_ips.add(ip)
print(f'IP {ip} bloqueado devido a tentativas em excesso na porta {port}')
# Aguardar e desbloquear IPs após o tempo de bloqueio
time.sleep(block_duration)
for ip in blocked_ips:
unblock_ip(ip)
print(f'IP {ip} desbloqueado após {block_duration} segundos de bloqueio')