iptables aliases for your linux machine

I have a very basic Linux VPS for testing and hosting web projects.

If you search through your logs, you will discover a whole world in terms of "hackers" and spammers trying to attack you. Don't take it personal ;)

One way to secure your VPS is to use iptables.

I can barely remember the exact commands to show, block and unblock IPs. If you are like me, here's a simple function alias :)

show-blocked() {
    echo "Blocked IP addresses:"
    sudo iptables -L INPUT -v -n | grep "DROP"
}

block-ip() {
    if [ -z "$1" ]; then
        echo "Usage: block-ip <IP_ADDRESS>"
        return 1
    fi
    sudo iptables -A INPUT -s "$1" -j DROP
    echo "Blocked IP: $1"
}

block-ip-range() {
    if [ -z "$1" ]; then
        echo "Usage: block-ip-range <IP_RANGE_ADDRESS>"
        return 1
    fi
    sudo iptables -A INPUT -m iprange --src-range "$1"  -j DROP
    echo "Blocked RANGE: $1"
}

unblock-ip() {
    if [ -z "$1" ]; then
        echo "Usage: unblock-ip <IP_ADDRESS>"
        return 1
    fi
    sudo iptables -D INPUT -s "$1" -j DROP
    echo "Unblocked IP: $1"
}

And you can use like this:

$ block-ip 5.39.1.243

$ unblock-ip 5.39.1.243

$ show-blocked

$ block-ip-range 5.39.1.243-5.39.1.200