UFW+IPSET 禁用非法IP

2024-12-02 11 0

#-A ufw-before-input -p tcp --dport  80 -m set --match-set banned_ips src -j DROP

# 创建ipset集合
ipset create banned_ips hash:ip hashsize 4096 maxelem 100000

# 删除ipset集合
ufw disable
ipset destroy banned_ips

# 添加/删除关联ip
ipset list banned_ips
ipset add banned_ips 14.29.182.126
ipset del banned_ips 14.29.182.126
vim /etc/ufw/before.rules

# Block traffic from banned IP addresses
-A ufw-before-input -m set --match-set banned_ips src -j DROP

# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT 

解决服务器重启 ufw 启动失败,导致无法连接外网

Dec 02 11:07:30 proxy51 ufw-init[594]: iptables-restore v1.6.1: Set banned_ips doesn't exist.
Dec 02 11:07:30 proxy51 ufw-init[594]: Error occurred at line: 79
Dec 02 11:07:30 proxy51 ufw-init[594]: Try `iptables-restore -h' or 'iptables-restore --help' for more information.
Dec 02 11:07:30 proxy51 systemd[1]: ufw.service: Main process exited, code=exited, status=1/FAILURE
Dec 02 11:07:30 proxy51 ufw-init[594]: Problem running '/etc/ufw/before.rules'
Dec 02 11:07:30 proxy51 systemd[1]: ufw.service: Failed with result 'exit-code'.
# /usr/local/bin/ipset-init.sh
#!/bin/bash

# 创建 ipset 列表(如果不存在)
ipset list banned_ips >/dev/null 2>&1
if [ $? -ne 0 ]; then
    ipset create banned_ips hash:ip hashsize 4096 maxelem 100000
fi

# 加入初始的 IP
ipset add banned_ips 183.48.123.219

# 删除旧规则(避免重复添加)
# iptables -D ufw-before-input -m set --match-set banned_ips src -j DROP 2>/dev/null

# 添加新规则
# iptables -I ufw-before-input -m set --match-set banned_ips src -j DROP
chmod +x /usr/local/bin/ipset-init.sh
# /etc/systemd/system/ipset-init.service
[Unit]
Description=Initialize ipset rules
Before=ufw.service
Wants=ufw.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/ipset-init.sh
RemainAfterExit=true

[Install]
WantedBy=multi-user.target
systemctl enable ipset-init

相关文章

ip_local_port_range: prefer different parity for start/end values
Linux Sudo 权限配置
阿里云ECS云盘IOPS压测
nextcloud preview-generate 报错文件无权限解决
tcpdump 抓包使用小结
Linux Tcpdump抓包

发布评论