一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Linux防火墙开启和关闭教程 firewalld与iptables配置

时间:2026-06-15 08:03:47 编辑:袖梨 来源:一聚教程网

firewalld服务在CentOS 7/8/Stream等系统中需通过systemctl启停并用firewall-cmd --state确认running状态;启用永久规则须先--permanent再--reload,且须确保网卡正确绑定到对应zone。

firewalld 服务启停与状态确认

CentOS 7/8/Stream、Fedora 等系统默认启用 firewalld,它不是“开关即生效”的简单服务,而是依赖运行时 + 永久配置双层机制。直接执行 systemctl stop firewalld 只会清空当前规则并停止守护进程,但不会影响已写入磁盘的 /etc/firewalld/ 配置;重启后若未禁用开机启动,服务仍会拉起并加载旧规则。

  • firewall-cmd --state 返回 running 才算真正活跃,仅看 systemctl status firewalld 显示 active (running) 不够 —— 有可能规则为空或 zone 错配
  • 关闭前务必确认是否已有业务依赖:比如 fail2ban 默认用 firewallcmd-ipset 动作,停掉 firewalld 会导致封禁失效
  • 永久禁用必须两步:先 systemctl stop firewalld,再 systemctl disable firewalld;漏掉后者,重启后自动复活

iptables 替代 firewalld 的实操要点

想换回 iptables 不是装完就完事。CentOS 7+ 中 iptables-services 包提供的是兼容层,底层实际调用 nftables(除非显式切换到 iptables-legacy)。直接启用 iptables 前,必须确保 firewalld 已彻底停用且未设置开机启动,否则两者冲突,iptables -L 可能显示空,而 firewall-cmd --list-all 却报错“not running”。

  • 安装命令是 yum install -y iptables-services,不是 iptables 单独包(后者不含 systemd 单元)
  • 启用后需执行 systemctl enable iptables,否则重启丢失规则 —— iptables-save > /etc/sysconfig/iptables 只保存,不绑定开机加载
  • iptables -I INPUT -p tcp --dport 22 -j ACCEPT 这类临时规则,不执行 iptables-save 就不会落盘,关机即丢

开放端口时 --permanent 和 --reload 的先后逻辑

firewall-cmd 开放端口,--permanent 参数只改配置文件,不触发现行策略;--reload 才把磁盘配置加载进内核。顺序错了,就会出现“明明加了规则却连不上”的情况。

  • 正确流程:先 firewall-cmd --permanent --add-port=80/tcp,再 firewall-cmd --reload
  • 误操作如先 --reload 再加规则,新规则只存在于运行时,下次 reload 会消失
  • firewall-cmd --query-port=80/tcp 查的是运行时状态,不是磁盘配置,所以它返回 no 并不代表没写入 permanent 配置
  • 如果用脚本批量开多个端口,建议统一加 --permanent 后一次性 --reload,避免反复重载损耗性能

iptables 与 firewalld 共存风险

两者不能同时管理同一张表。firewalld 默认使用 nftables 后端,而传统 iptables 命令在新版系统中其实是 iptables-nft 别名;若手动运行 iptables-legacy,又启着 firewalld,会出现规则互相覆盖、iptables -Lfirewall-cmd --list-all 输出不一致、甚至连接中断。

  • 检查当前底层:运行 ls /proc/sys/net/netfilter/,有内容说明 nftables 活跃;iptables -V 输出含 “nf_tables” 表示走 nft 后端
  • 真要混用,必须明确指定:iptables-legacy -L vs iptables-nft -L,但强烈不建议
  • 生产环境切防火墙方案前,先在测试机验证 ss -tlnp | grep :端口号 和实际 telnet 连通性,别只信命令返回
实际部署中最容易被忽略的是:firewalld 的 zone 绑定和接口归属。哪怕开了 80 端口,如果网卡没在 public zone 下,或者被错误分配到 drop zone,流量照样被丢。查用 firewall-cmd --get-active-zones,改用 firewall-cmd --zone=public --change-interface=eth0

热门栏目