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.


import socket
import sys
import os

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

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

def valid_ipv6(address):
                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])
elif valid_ipv6(sys.argv[1]) == 1:
        print("Banning IPv6 address: " + sys.argv[1])
        print("Please supply a valid IP address")

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

using it is quite simple:


Hope this is of some use to you!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s