温馨提示×

centos防火墙如何限制ip

小樊
57
2026-10-11 17:38:07
栏目: 智能运维

在 CentOS 中限制 IP(封 IP / 只允许某些 IP 访问)通常取决于系统使用的防火墙:

  • CentOS 6 及以前:iptables
  • CentOS 7 / 8 / Stream:firewalld(底层仍是 iptables/nftables)

下面分别说明。


一、CentOS 7/8/Stream(firewalld,推荐)

1️⃣ 禁止某个 IP 访问(封 IP)

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="1.2.3.4" reject'

或彻底丢弃(更狠):

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="1.2.3.4" drop'

重新加载:

firewall-cmd --reload

2️⃣ 禁止某个 IP 段

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" drop'
firewall-cmd --reload

3️⃣ 只允许某个 IP 访问(白名单)

例如只允许 8.8.8.8:

firewall-cmd --permanent --set-default-zone=drop
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="8.8.8.8" accept'
firewall-cmd --reload

⚠️ 谨慎操作,避免把自己关在外面(建议先保留 SSH IP)


4️⃣ 限制某 IP 访问特定端口(如 22)

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="1.2.3.4" port protocol="tcp" port="22" reject'
firewall-cmd --reload

二、CentOS 6 或更早(iptables)

1️⃣ 封单个 IP

iptables -A INPUT -s 1.2.3.4 -j DROP
service iptables save
service iptables restart

2️⃣ 封 IP 段

iptables -A INPUT -s 192.168.1.0/24 -j DROP

3️⃣ 只允许某 IP 访问 22 端口

iptables -A INPUT -p tcp --dport 22 -s 8.8.8.8 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP

三、查看当前规则

firewalld

firewall-cmd --list-all
firewall-cmd --list-rich-rules

iptables

iptables -L -n

四、常见建议

  • 改防火墙前,确保有可用 SSH 通道
  • 生产环境优先用 firewall-cmd --permanent
  • 临时测试可不加 --permanent

如果你能告诉我:

  • CentOS 版本
  • 想 封 IP / 只允许 IP / 限制端口
  • 是否用于 SSH / Web / 数据库

我可以给你更精确的命令。

0 踩