CentOS防火墙的开启与关闭:全面指南(支持CentOS 7/8/9及旧版本)

在Linux服务器运维过程中,防火墙管理是保障系统安全与服务连通性的关键环节。作为广泛使用的服务器操作系统,CentOS 的防火墙机制在不同版本中有所差异,尤其是从 CentOS 6 到 CentOS 7+ 的版本迭代中,防火墙管理工具发生了重大变化。

CentOS防火墙的开启与关闭:全面指南(支持CentOS 7/8/9及旧版本)

本文将为你详细介绍 CentOS系统中防火墙的开启、关闭、状态查看及安全建议,涵盖 CentOS 7、8、9(使用 firewalld)和 CentOS 6及更早版本(使用 iptables),帮助你精准操作,避免因配置错误导致服务中断或安全风险。


CentOS 防火墙机制概览

CentOS 版本防火墙服务管理工具
CentOS 7 / 8 / 9firewalldsystemctlfirewall-cmd
CentOS 6 及更早iptablesservicechkconfig

⚠️ 重要提示:现代CentOS系统(7及以上)默认使用 firewalld,不推荐直接操作 iptables,以免造成规则冲突。


CentOS 7/8/9 防火墙管理(firewalld)

1. 查看防火墙当前状态

在进行任何操作前,建议先检查防火墙运行状态:

sudo systemctl status firewalld
  • 若显示 active (running),表示防火墙正在运行。

  • 若显示 inactive (dead),表示防火墙已关闭。

你也可以使用专用命令查看:

sudo firewall-cmd --state

返回 runningnot running


2. 临时关闭防火墙(重启后恢复)

如果你需要临时关闭防火墙以调试网络或服务,可执行:

sudo systemctl stop firewalld

此命令会立即停止防火墙服务,但系统重启后会自动恢复,适合测试环境使用。


3. 永久关闭防火墙(禁止开机启动)

若需永久禁用防火墙(如内网测试环境),请执行以下两步:

sudo systemctl stop firewalld          # 停止当前服务
sudo systemctl disable firewalld       # 禁用开机自启

执行后,系统重启也不会自动启动防火墙。


4. 重新开启防火墙

如需重新启用防火墙,命令如下:

sudo systemctl start firewalld         # 立即启动
sudo systemctl enable firewalld        # 设置开机自启

5. 使用 firewall-cmd 临时关闭(可选)

firewall-cmd 也支持临时关闭:

sudo firewall-cmd --panic-on           # 启用紧急模式(所有流量禁止)
sudo firewall-cmd --panic-off          # 关闭紧急模式

或直接停止服务(同上):

sudo firewall-cmd --reload             # 重载配置(不关闭)

🔍 建议:日常管理推荐使用 systemctl,更稳定且符合现代Linux服务管理规范。


CentOS 6 及更早版本(iptables)

对于仍在使用旧版系统的用户,需使用 iptables 服务进行管理。

1. 查看防火墙状态

sudo service iptables status

若提示 Firewall is not running,则表示已关闭。


2. 临时关闭防火墙

sudo service iptables stop

立即停止 iptables 服务,重启后恢复。


3. 永久关闭防火墙

sudo chkconfig iptables off

此命令将禁止 iptables 在系统启动时自动运行。


4. 重新启用 iptables

sudo service iptables start
sudo chkconfig iptables on

安全建议与最佳实践

虽然关闭防火墙可以简化网络调试,但强烈不建议在生产环境中完全关闭防火墙。以下是几点安全建议:

推荐做法

  • 仅开放必要端口:如HTTP(80)、HTTPS(443)、SSH(22)等。

  • 使用 firewall-cmd 添加规则,例如:

sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload

生产环境建议

  • 配置 firewalld 的 zone 策略,区分内外网流量。

  • 定期审查防火墙规则,避免冗余或危险配置。

  • 结合 fail2ban 等工具增强安全防护。

避免操作

  • 不要随意清空 iptables 规则(iptables -F)。

  • 避免在无备份情况下修改防火墙配置。

  • 生产服务器切勿永久关闭防火墙。


常见问题解答(FAQ)

Q1:关闭防火墙后 SSH 连接不上怎么办?

A:可能是网络策略或云平台安全组限制。建议通过VNC或控制台登录,重新启用防火墙并开放22端口。

Q2:systemctl disable firewalld 提示“Unit is masked”?

A:说明服务已被“屏蔽”。需先解绑:

sudo systemctl unmask firewalld
sudo systemctl disable firewalld

Q3:如何查看已开放的端口?

sudo firewall-cmd --list-ports
sudo firewall-cmd --list-all
操作CentOS 7+/8/9CentOS 6
查看状态systemctl status firewalldservice iptables status
临时关闭systemctl stop firewalldservice iptables stop
永久关闭systemctl disable firewalldchkconfig iptables off
重新启用systemctl start enable firewalldservice iptables start + chkconfig on

📌 核心建议:优先使用 systemctl 管理现代CentOS系统防火墙,避免直接操作底层规则。安全与便利需平衡,关闭防火墙应作为最后手段


关注我,获取更多Linux运维、服务器安全与DevOps实战技巧!
📌 记得点赞收藏,转发给需要的小伙伴!

发表评论

评论列表

还没有评论,快来说点什么吧~