使用宝塔面板经常遇到恶意 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 日志文件这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.