温馨提示×

CentOS怎样替换防火墙

小樊
63
2026-07-09 07:29:28
栏目: 智能运维

在 CentOS 中,“替换防火墙”通常指从默认的 firewalld 切换到 iptables,或者反过来。下面按常见场景给你完整的操作说明,先确认版本再操作。


一、CentOS 版本说明

  • CentOS 7 / 8 / Stream:默认使用 firewalld
  • CentOS 6:默认使用 iptables(已停止维护,不建议使用)

✅ 下面以 CentOS 7+ 为例。


二、从 firewalld 切换到 iptables(最常见)

1️⃣ 关闭并禁用 firewalld

systemctl stop firewalld
systemctl disable firewalld

2️⃣ 安装 iptables 服务

yum install -y iptables-services

3️⃣ 启动并设置开机自启

systemctl start iptables
systemctl enable iptables

4️⃣ 查看当前规则

iptables -L -n

5️⃣ 示例:允许 SSH(22端口)

iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

6️⃣ 保存规则(非常重要)

service iptables save
# 或
iptables-save > /etc/sysconfig/iptables

三、从 iptables 切换回 firewalld

1️⃣ 停止 iptables

systemctl stop iptables
systemctl disable iptables

2️⃣ 启用 firewalld

systemctl start firewalld
systemctl enable firewalld

3️⃣ 基本使用示例

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

四、CentOS 8 / Stream 注意事项

CentOS 8 默认:

  • firewalld
  • iptables ❌(已废弃,使用 nftables)

CentOS 8 如果要使用 iptables:

yum install -y iptables-services

不推荐


五、关于 nftables(进阶)

CentOS 8+ 实际底层是:

firewalld → nftables

查看当前防火墙后端:

firewall-cmd --get-backend

六、如何选择?

场景 推荐
新手 / 云服务器 firewalld
老系统 / 兼容脚本 iptables
新系统 firewalld(nftables)

七、常见坑

❌ 同时启用 firewalld + iptables
❌ 修改规则后忘记保存
❌ 误关 22 端口导致 SSH 断开


如果你愿意,可以告诉我:

  • ✅ CentOS 版本
  • ✅ 是云服务器还是本地
  • ✅ 想实现什么(放行端口 / 限制 IP / 防攻击)

我可以给你精确的一键配置命令

0