Banning IP addresses using ufw

It’s been a while!

ufw is a popular frontend for iptables. Sometimes you just really need to get rid of an IP address that’s knocking on the doors for no good reason. This is where the pyban script comes in handy.

It’s a simple little python script that just bans incoming connections from the IP address in question.

#!/usr/bin/python3

import socket
import sys
import os


if len(sys.argv) != 2:
        print("Invalid number of Arguments")
        sys.exit(0)

def valid_ipv4(address):
        try:
                socket.inet_aton(address)
                return 1
        except socket.error:
#               print("Invalid IP Address")
                return 0

def valid_ipv6(address):
        try:
                socket.inet_pton(socket.AF_INET6, address)
                return 1
        except socket.error:
#               print("Not IPv6 either!")
                return 0

commandstring = "ufw insert 1 deny from " + sys.argv[1] + " comment pyban"

if valid_ipv4(sys.argv[1]) == 1:
        print("Banning IP address: " + sys.argv[1])
        os.system(commandstring)
        sys.exit(0)
elif valid_ipv6(sys.argv[1]) == 1:
        print("Banning IPv6 address: " + sys.argv[1])
        os.system(commandstring)
        sys.exit(0)
else:
        print("Please supply a valid IP address")
        sys.exit(0)

Save the script to to a file called “pyban” and make it executable.

using it is quite simple:

pyban 192.0.2.20

Hope this is of some use to you!

Leave a comment