Advertisement
ofmarconi

Mitigate port scanning

Sep 16th, 2023
1,322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. import subprocess
  2. import re
  3. import collections
  4. import time
  5.  
  6. # Configurações
  7. log_file = '/var/log/syslog'
  8. threshold = 4
  9. block_duration = 86400  # 24 horas em segundos
  10. ip_count = collections.defaultdict(int)
  11. blocked_ips = set()
  12.  
  13. # Função para bloquear IP
  14. def block_ip(ip):
  15.     subprocess.run(['sudo', 'csf', '-d', ip])
  16.  
  17. # Função para desbloquear IP
  18. def unblock_ip(ip):
  19.     subprocess.run(['sudo', 'csf', '-dr', ip])
  20.  
  21. # Monitorar o log
  22. with open(log_file, 'r') as f:
  23.     lines = f.readlines()
  24.  
  25. for line in lines:
  26.     match = re.search(r'SRC=(\d+\.\d+\.\d+\.\d+).*DPT=(\d+)', line)
  27.     if match:
  28.         ip = match.group(1)
  29.         port = match.group(2)
  30.         ip_count[ip] += 1
  31.         if ip_count[ip] >= threshold and ip not in blocked_ips:
  32.             block_ip(ip)
  33.             blocked_ips.add(ip)
  34.             print(f'IP {ip} bloqueado devido a tentativas em excesso na porta {port}')
  35.  
  36. # Aguardar e desbloquear IPs após o tempo de bloqueio
  37. time.sleep(block_duration)
  38. for ip in blocked_ips:
  39.     unblock_ip(ip)
  40.     print(f'IP {ip} desbloqueado após {block_duration} segundos de bloqueio')
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement