Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

How to Create a Simple IP Blocker Script Using iptables and Fail2Ban

Published

Website Security

Every day, servers face attacks from hackers and bots trying to break in. These attacks can slow down your website, steal data, or even crash your server completely. Without proper protection, your server is like a house with no locks on the doors. The good news is that Linux provides powerful tools to protect your system automatically. In this guide, we will learn how to use iptables and Fail2Ban together to create a simple but effective IP blocking system. These tools will watch your server and block bad actors before they can cause damage.

What are iptables and Fail2Ban?

iptables is a firewall for Linux. It controls who can connect to your server. You can block bad IP addresses with it.

Fail2Ban watches log files. When someone tries to hack your server many times, it blocks their IP address using iptables.

Why Block IP Addresses?

We block IPs to stop:

  • People trying to guess passwords
  • Attacks that slow down your server
  • Spam messages
  • Bad bots
  • Hackers

Installing the Tools

First, we need to install both tools.

Installing iptables

Most Linux systems have iptables already. Check if you have it:

iptables --version

If not, install it:

Ubuntu/Debian:

sudo apt update
sudo apt install iptables

CentOS/RHEL:

sudo yum install iptables

Installing Fail2Ban

Ubuntu/Debian:

sudo apt update
sudo apt install fail2ban

CentOS/RHEL:

sudo yum install epel-release
sudo yum install fail2ban

Basic iptables Commands

Here are simple commands to use iptables:

Block One IP Address

sudo iptables -A INPUT -s 192.168.1.100 -j DROP

Block Many IP Addresses

sudo iptables -A INPUT -s 192.168.1.0/24 -j DROP

See Blocked IPs

sudo iptables -L

Unblock an IP

sudo iptables -D INPUT -s 192.168.1.100 -j DROP

Save Rules

sudo mkdir -p /etc/iptables
sudo iptables-save > /etc/iptables/rules.v4

Setting Up Fail2Ban

Fail2Ban uses files called jails. These tell it what to watch and what to do.

Basic Setup

Copy the config file:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Edit it:

sudo nano /etc/fail2ban/jail.local

Add these settings:

[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 1800

This will ban IPs for 1 hour if they try to login wrong 3 times.

Creating a Simple IP Blocker Script

Let’s make a script to help block IPs easily.

Create a file called block_ip.sh:

#!/bin/bash
# Simple IP Blocker
LOG_FILE="/var/log/ip_blocker.log"

# Write to log
write_log() {
    echo "$(date): $1" >> $LOG_FILE
    echo "$1"
}

# Block an IP
block_ip() {
    ip=$1
    
    # Check if already blocked
    if iptables -L INPUT -n | grep -q $ip; then
        write_log "IP $ip already blocked"
        return
    fi
    
    # Block it
    iptables -A INPUT -s $ip -j DROP
    write_log "Blocked IP: $ip"
}

# Unblock an IP
unblock_ip() {
    ip=$1
    iptables -D INPUT -s $ip -j DROP
    write_log "Unblocked IP: $ip"
}

# Show blocked IPs
list_blocked() {
    echo "Blocked IPs:"
    iptables -L INPUT -n | grep DROP
}

# What to do
case "$1" in
    "block")
        block_ip $2
        ;;
    "unblock")
        unblock_ip $2
        ;;
    "list")
        list_blocked
        ;;
    *)
        echo "Use: $0 {block|unblock|list} [ip]"
        echo "block 1.2.3.4    - Block this IP"
        echo "unblock 1.2.3.4 - Unblock this IP"
        echo "list            - Show blocked IPs"
        ;;
esac

Make Script Work:

sudo chmod +x block_ip.sh
sudo mv block_ip.sh /usr/local/bin/

Use the Script

# Block an IP

sudo block_ip.sh block 192.168.1.100

# Unblock an IP

sudo block_ip.sh unblock 192.168.1.100

# See blocked IPs

sudo block_ip.sh list

Better Script with Safe List

This version has a safe list so you don’t block good IPs:

#!/bin/bash
# IP Blocker with Safe List
SAFE_LIST="/etc/safe_ips.txt"
LOG_FILE="/var/log/ip_blocker.log"

# Ensure safe list exists
if [ ! -f "$SAFE_LIST" ]; then
    echo "127.0.0.1" > "$SAFE_LIST"
    echo "192.168.1.0/24" >> "$SAFE_LIST"
fi

# Check if IP is safe
is_safe() {
    local ip="$1"
    grep -qw "$ip" "$SAFE_LIST"
}

# Check if already blocked
is_blocked() {
    local ip="$1"
    iptables -C INPUT -s "$ip" -j DROP 2>/dev/null
}

# Block IP safely
safe_block() {
    local ip="$1"
    if [ -z "$ip" ]; then
        echo "❌ No IP provided"
        exit 1
    fi
    if is_safe "$ip"; then
        echo "❌ Cannot block safe IP: $ip"
        exit 1
    fi
    if is_blocked "$ip"; then
        echo "⚠️ Already blocked: $ip"
        exit 0
    fi
    iptables -A INPUT -s "$ip" -j DROP
    echo "$(date): Blocked $ip" >> "$LOG_FILE"
    echo "✅ Blocked IP: $ip"
}

# Add IP to safe list
add_safe() {
    local ip="$1"
    if [ -z "$ip" ]; then
        echo "❌ No IP provided"
        exit 1
    fi
    if ! grep -qw "$ip" "$SAFE_LIST"; then
        echo "$ip" >> "$SAFE_LIST"
        echo "✅ Added $ip to safe list"
    else
        echo "⚠️ $ip already in safe list"
    fi
}

# CLI Interface
case "$1" in
    block)
        safe_block "$2"
        ;;
    add_safe)
        add_safe "$2"
        ;;
    *)
        echo "Usage: $0 {block |add_safe }"
        exit 1
        ;;
esac

Working with Fail2Ban

Make Fail2Ban use your script.

Create /etc/fail2ban/action.d/my-blocker.conf:

[Definition]
actionban = /usr/local/bin/block_ip.sh block 
actionunban = /usr/local/bin/block_ip.sh unblock 

Update jail config:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 1800
action = my-blocker

Keep Your System Safe

Check Logs Often

tail -f /var/log/ip_blocker.log

See Fail2Ban Status

sudo fail2ban-client status

Backup Rules

Make a backup script:

#!/bin/bash
# backup.sh
iptables-save > /backup/iptables-$(date +%Y%m%d).rules

Auto-Save Rules

Make rules stay after restart:

sudo apt install iptables-persistent

Fix Common Problems

Rules Gone After Restart

Save rules:

sudo iptables-save > /etc/iptables/rules.v4

Fail2Ban Won’t Start

Check config:

sudo fail2ban-client -t

Blocked Yourself

Clear all blocks:

iptables -F INPUT

Watch for Problems

Make a check script:

#!/bin/bash
# check.sh
BLOCKS=$(iptables -L INPUT -n | grep DROP | wc -l)
if [ $BLOCKS -gt 50 ]; then
    echo "Too many blocked IPs: $BLOCKS"
fi

Run every hour:

crontab -e
# Add: 0 * * * * /usr/local/bin/check.sh

Conclusion

IP blocking keeps your server safe. Use iptables and Fail2Ban together. Start simple and add more features later.

Remember to:

  • Test before using on real servers
  • Keep safe lists updated
  • Check logs often
  • Make backups
  • Have a way to fix problems

Your server will be much safer with good IP blocking. Bad people will find it harder to attack you.

Related guides

Account services are unavailable until the production backend is configured.