Advertisement
AceScottie

block_ips.py

Apr 11th, 2020
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. import os
  2.  
  3.  
  4. def get_connected_ips():
  5.     ips = os.popen("netstat -tn 2>/dev/null | grep :80 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head")
  6.  
  7.     x = ips.read()
  8.     x = x.replace("\n", " ")
  9.     x=x.split(" ")
  10.  
  11.     ip_addresses = []
  12.     for i in x:
  13.         if len(i) > 3:
  14.             ip_addresses.append(i)
  15.  
  16.     return ip_addresses
  17.  
  18. def run():
  19.     to_block = []
  20.     cur_connected = get_connected_ips()
  21.     for ip in cur_connected:
  22.         if not ip in to_block:
  23.             to_block.append(ip)
  24.     return to_block
  25.  
  26. if __name__ == "__main__":
  27.     try:
  28.         blocked = []
  29.         while True:
  30.             try:
  31.                 blocking = run()
  32.                 for ip in blocking:
  33.                     if ip not in blocked:
  34.                         os.system("iptables -I FORWARD -s %s/24 -j DROP"%ip)
  35.                         blocked.append(ip)
  36.  
  37.             except KeyboardInterrupt:
  38.                 os.system("iptables-save | awk ' !x[$0]++' | iptables-restore")
  39.                 out = os.popen("iptables -L")
  40.                 print(out.read())
  41.                 break
  42.     except:
  43.         raise
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement