CentOS 中的 iptables 和 firewalld 都是用于配置防火墙规则的工具,但它们在使用和管理上有所不同。iptables 是一个底层的命令行工具,而 firewalld 是一个更高层次的抽象,它使用 iptables 作为其后端来实际设置规则。在 CentOS 7 及以上版本中,默认的防火墙管理工具是 firewalld。
如果你想要让 iptables 和 firewalld 协同工作,通常的做法是通过 firewalld 来管理防火墙规则,因为 firewalld 提供了一个更友好的接口和动态管理区域的能力。然而,如果你需要直接使用 iptables 命令来设置规则,你可以这样做,但需要注意不要与 firewalld 的设置冲突。
以下是一些基本的步骤来使用 firewalld:
启动 firewalld 服务:
sudo systemctl start firewalld
设置防火墙开机自启:
sudo systemctl enable firewalld
查看当前防火墙状态:
sudo firewall-cmd --state
查看所有开放的端口:
sudo firewall-cmd --list-all
添加一个端口到防火墙规则(例如,开放 TCP 端口 80):
sudo firewall-cmd --permanent --zone=public --add-port=80/tcp
重新加载防火墙配置:
sudo firewall-cmd --reload
如果你确实需要直接使用 iptables 命令,你可以这样做,但请确保你知道自己在做什么,并且了解这些规则可能会被 firewalld 覆盖:
# 添加一个规则到 INPUT 链
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# 保存 iptables 规则(CentOS 7 及以上版本使用 systemctl 来保存 firewalld 规则,而不是直接保存 iptables)
sudo systemctl restart firewalld
请注意,直接使用 iptables 设置的规则不会持久化,系统重启后规则会丢失。而 firewalld 提供了持久化规则的方法。
在大多数情况下,建议只使用 firewalld 来管理防火墙规则,因为它提供了更简单和更动态的方式来处理防火墙配置。如果你确实需要使用 iptables,请确保你了解如何避免与 firewalld 的规则冲突,并且知道如何同步两者的配置。