如何编写IP封禁脚本

wen 实用脚本 26

本文目录导读:

如何编写IP封禁脚本

  1. 基本思路
  2. Linux系统(使用iptables)
  3. 使用fail2ban(推荐)
  4. Python脚本版本
  5. 自动化检测脚本
  6. Windows系统(PowerShell)
  7. 使用建议

我来为您介绍几种编写IP封禁脚本的方法,从简单到复杂。

基本思路

IP封禁脚本的核心逻辑:

  • 检测异常IP(如多次登录失败)
  • 将IP加入黑名单
  • 使用防火墙规则封禁

Linux系统(使用iptables)

手动封禁单个IP

#!/bin/bash
# block_ip.sh - 封禁单个IP
IP=$1
# 验证IP格式
if [[ ! $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    echo "无效的IP地址"
    exit 1
fi
# 添加封禁规则
iptables -A INPUT -s $IP -j DROP
echo "IP $IP 已被封禁"
# 保存规则(CentOS/RHEL)
service iptables save
# 或使用 iptables-save > /etc/iptables/rules.v4 (Debian/Ubuntu)

批量封禁(从文件读取)

#!/bin/bash
# batch_block.sh - 批量封禁IP
BLOCKLIST="/etc/blocked_ips.txt"
if [ ! -f "$BLOCKLIST" ]; then
    echo "黑名单文件不存在"
    exit 1
fi
while IFS= read -r ip; do
    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        iptables -C INPUT -s $ip -j DROP 2>/dev/null || \
        iptables -A INPUT -s $ip -j DROP
        echo "已封禁: $ip"
    fi
done < "$BLOCKLIST"
# 保存规则
iptables-save > /etc/iptables/rules.v4

使用fail2ban(推荐)

fail2ban是最常用的自动封禁工具:

安装和配置

# 安装fail2ban
apt-get install fail2ban  # Debian/Ubuntu
# 或 yum install fail2ban  # CentOS/RHEL
# 创建本地配置
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

配置SSH防暴力破解

# /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600
findtime = 600

自定义规则

#!/bin/bash
# custom_fail2ban.sh - 自定义封禁规则
# 封禁频繁访问的IP
fail2ban-client set sshd banip 192.168.1.100
# 查看封禁状态
fail2ban-client status sshd
# 解封IP
fail2ban-client set sshd unbanip 192.168.1.100

Python脚本版本

#!/usr/bin/env python3
# ip_blocker.py - Python IP封禁脚本
import subprocess
import re
import sys
class IPBlocker:
    def __init__(self):
        self.iptables_path = "/sbin/iptables"
    def validate_ip(self, ip):
        """验证IP地址格式"""
        pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
        if not re.match(pattern, ip):
            return False
        # 验证每个段在0-255之间
        parts = ip.split('.')
        return all(0 <= int(part) <= 255 for part in parts)
    def block_ip(self, ip):
        """封禁IP"""
        if not self.validate_ip(ip):
            print(f"无效IP: {ip}")
            return False
        try:
            # 检查规则是否已存在
            check_cmd = [self.iptables_path, "-C", "INPUT", "-s", ip, "-j", "DROP"]
            result = subprocess.run(check_cmd, capture_output=True)
            if result.returncode != 0:
                # 添加新规则
                block_cmd = [self.iptables_path, "-A", "INPUT", "-s", ip, "-j", "DROP"]
                subprocess.run(block_cmd, check=True)
                print(f"已封禁: {ip}")
                return True
            else:
                print(f"IP {ip} 已被封禁")
                return True
        except subprocess.CalledProcessError as e:
            print(f"封禁失败: {e}")
            return False
    def unblock_ip(self, ip):
        """解封IP"""
        if not self.validate_ip(ip):
            print(f"无效IP: {ip}")
            return False
        try:
            unblock_cmd = [self.iptables_path, "-D", "INPUT", "-s", ip, "-j", "DROP"]
            subprocess.run(unblock_cmd, check=True)
            print(f"已解封: {ip}")
            return True
        except subprocess.CalledProcessError as e:
            print(f"解封失败: {e}")
            return False
    def list_blocked(self):
        """列出被封禁的IP"""
        try:
            list_cmd = [self.iptables_path, "-L", "INPUT", "-n"]
            result = subprocess.run(list_cmd, capture_output=True, text=True)
            print("当前封禁规则:")
            print(result.stdout)
        except Exception as e:
            print(f"查询失败: {e}")
# 使用示例
if __name__ == "__main__":
    blocker = IPBlocker()
    if len(sys.argv) < 2:
        print("用法: python ip_blocker.py [block|unblock|list] [IP地址]")
        sys.exit(1)
    action = sys.argv[1]
    if action == "block" and len(sys.argv) == 3:
        blocker.block_ip(sys.argv[2])
    elif action == "unblock" and len(sys.argv) == 3:
        blocker.unblock_ip(sys.argv[2])
    elif action == "list":
        blocker.list_blocked()
    else:
        print("无效命令")

自动化检测脚本

#!/bin/bash
# auto_block.sh - 自动检测并封禁异常IP
LOG_FILE="/var/log/auth.log"
BLOCKED_FILE="/tmp/blocked_ips.txt"
MAX_ATTEMPTS=5
TIME_WINDOW=300  # 5分钟
# 检测SSH暴力破解
tail -f $LOG_FILE | while read line; do
    if echo "$line" | grep -q "Failed password"; then
        IP=$(echo "$line" | grep -oP 'from \K[0-9.]+')
        # 统计该IP在时间窗口内的失败次数
        COUNT=$(grep "Failed password.*from $IP" $LOG_FILE | \
                awk -v now=$(date +%s) -v window=$TIME_WINDOW \
                '{print systime() - window}' | \
                wc -l)
        if [ $COUNT -ge $MAX_ATTEMPTS ]; then
            # 检查是否已封禁
            if ! grep -q $IP $BLOCKED_FILE 2>/dev/null; then
                iptables -A INPUT -s $IP -j DROP
                echo $IP >> $BLOCKED_FILE
                echo "$(date): 已封禁异常的IP: $IP (失败次数: $COUNT)"
            fi
        fi
    fi
done

Windows系统(PowerShell)

# block_ip.ps1 - Windows防火墙封禁脚本
param(
    [string]$Action = "block",
    [string]$IPAddress
)
# 验证IP
function Validate-IP {
    param($ip)
    return $ip -match '^(\d{1,3}\.){3}\d{1,3}$'
}
# 封禁IP
function Block-IP {
    param($ip)
    $ruleName = "Block_$ip"
    try {
        New-NetFirewallRule -DisplayName $ruleName `
            -Direction Inbound `
            -RemoteAddress $ip `
            -Action Block `
            -Profile Any
        Write-Host "已封禁: $ip" -ForegroundColor Green
    }
    catch {
        Write-Error "封禁失败: $_"
    }
}
# 解封IP
function Unblock-IP {
    param($ip)
    $ruleName = "Block_$ip"
    try {
        Remove-NetFirewallRule -DisplayName $ruleName
        Write-Host "已解封: $ip" -ForegroundColor Yellow
    }
    catch {
        Write-Error "解封失败: $_"
    }
}
# 主逻辑
if ($Action -eq "block" -and $IPAddress) {
    if (Validate-IP $IPAddress) {
        Block-IP $IPAddress
    } else {
        Write-Error "无效IP地址"
    }
}
elseif ($Action -eq "unblock" -and $IPAddress) {
    Unblock-IP $IPAddress
}
else {
    Write-Host "用法: .\block_ip.ps1 -Action [block|unblock] -IPAddress x.x.x.x"
}

使用建议

  1. 测试环境验证:先在测试环境运行
  2. 添加白名单:不要封禁自己的IP
  3. 设置时间限制:使用iptables的time模块设置自动解封
  4. 日志记录:记录封禁操作便于审计

选择哪种方式取决于您的需求:

  • 简单封禁:使用iptables直接操作
  • 自动防护:推荐fail2ban
  • 自定义需求:Python脚本更灵活

需要我详细解释某个特定场景的实现吗?

抱歉,评论功能暂时关闭!