使用宝塔面板经常遇到恶意 IP 攻击,需要手动封禁,非常麻烦。
在开始之前,请确保已经:
想要用 bt cli 实现,没有发现入口,先用 python 脚本实现。
首先,我们需要创建一个 Python 脚本来实现自动化封禁。登录宝塔面板后,在 /www/server/panel/plugin/ 目录下创建 ip_intel.py 文件:
#!/usr/bin/python3
import requests
import subprocess
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(
    filename='/www/server/panel/logs/ip_intel.log',
    level=logging.INFO,
    format='%(asctime)s - %(message)s'
)
# 长亭 IP 恶意情报库订阅地址
API_URL = "https://ip-0.rivers.chaitin.cn/api/share/ip_group/xxxxxxxxxxxxxxxxxxxxxxxx?format=cidr"
def get_malicious_ips():
    """获取恶意 IP 列表"""
    try:
        response = requests.get(API_URL)
        ip_list = response.content.decode('utf-8').split('\n')
        return [ip.strip() for ip in ip_list if ip.strip()]
    except Exception as e:
        logging.error(f"获取恶意 IP 列表失败: {str(e)}")
        return []
def update_iptables_rules():
    """更新 iptables 规则"""
    try:
        # 创建新的 chain (如果不存在)
        subprocess.run("iptables -N CHAITIN_BLOCK 2>/dev/null || true", shell=True)
        # 清空现有规则
        subprocess.run("iptables -F CHAITIN_BLOCK", shell=True)
        # 确保 chain 被引用(如果还没有)
        subprocess.run("iptables -C INPUT -j CHAITIN_BLOCK 2>/dev/null || iptables -I INPUT -j CHAITIN_BLOCK", shell=True)
        # 获取恶意 IP 列表并添加规则
        ips = get_malicious_ips()
        for ip in ips:
            cmd = f"iptables -A CHAITIN_BLOCK -s {ip} -j DROP"
            subprocess.run(cmd, shell=True)
            logging.info(f"已添加封禁规则: {ip}")
        logging.info(f"规则更新完成,共添加 {len(ips)} 条规则")
    except Exception as e:
        logging.error(f"更新防火墙规则失败: {str(e)}")
if __name__ == "__main__":
    update_iptables_rules()
在宝塔面板中添加定时任务,实现自动更新:
更新长亭 IP 威胁情报python3 /www/server/panel/plugin/ip_intel.py完成配置后,您可以通过以下方式查看防护效果:
/www/server/panel/logs/ip_intel.log 日志文件|  |      1ncmonster      352 天前 宝塔明明可以直接在界面上封 IP ,何必搞这么复杂 | 
|      3JKOR      352 天前 加个双向 tls 验证更安全 | 
|  |      6wu67      352 天前 via Android 不要只用 iptable ,考虑组合 ipset 使用。 而且自动获取看起来很美好,实际上有个很大的问题,上游的 ip 数据不一定可靠,到时候就会喜提服务器高负载宕机,别问我怎么知道的... | 
|      7aeron      352 天前 我是服务器上开几个钓鱼端口,除了一些白名单的之外,其他的哪个 IP 访问封哪个, |