服务器批量封禁 IP和屏蔽域名

  |   0 评论   |   0 浏览

第一步:批量封禁 IP(使用 firewalld + ipset)

这是 UOS 官方推荐的高性能方案,适合处理大量 IP。

1.1 确保 firewalld 已启动

bash

sudo systemctl start firewalld
sudo systemctl enable firewalld

1.2 创建一个 ipset 集合(名字叫 blocklist)

bash

sudo firewall-cmd --permanent --new-ipset=blocklist --type=hash:net

1.3 将 ip_list.txt 中的所有 IP 批量导入集合

bash

while read ip; do
    sudo firewall-cmd --permanent --ipset=blocklist --add-entry="$ip"
done < ip_list.txt

注意 :如果 IP 数量有几百上千条,这个循环可能需要几十秒到几分钟,请耐心等待。执行期间不会有报错输出,耐心等待命令结束即可。

1.4 创建防火墙规则,拒绝所有黑名单 IP 访问

bash

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source ipset="blocklist" reject'

1.5 重载防火墙让规则生效

bash

sudo firewall-cmd --reload

1.6 验证是否生效

bash

sudo firewall-cmd --list-all

你应该能看到输出中包含 rule family="ipv4" source ipset="blocklist" reject 这一行。


第二步:批量屏蔽域名(修改 /etc/hosts)

2.1 备份原文件(好习惯)

bash

sudo cp /etc/hosts /etc/hosts.bak

2.2 将 domain_list.txt 中的域名批量写入 /etc/hosts

bash

while read domain; do
    echo "0.0.0.0 $domain"
done < domain_list.txt | sudo tee -a /etc/hosts

说明0.0.0.0 是一个无效地址,所有访问这些域名的请求都会被导向本地,从而无法连接。

2.3 验证是否添加成功

bash

tail -n 20 /etc/hosts

你应该能看到最后几行是 0.0.0.0 开头的域名列表。

2.4 刷新本地 DNS 缓存(确保立即生效)

bash

sudo systemctl restart nscd 2>/dev/null || sudo resolvectl flush-caches 2>/dev/null

(这条命令若报错忽略即可,大部分情况下修改 hosts 是即时生效的)


标题:服务器批量封禁 IP和屏蔽域名
作者:zytops
地址:https://zytops.com/articles/2026/06/25/1782355256849.html