需先确认 iptables 或 firewalld 服务状态及规则是否为空,再按工具分别配置:iptables 清空规则、设默认策略为 DROP、放行回环与已建立连接、保存规则;firewalld 则启用服务、设置默认区域、添加服务或端口并重载。

如果您在 Linux 系统中需要对网络流量进行控制,但尚未配置 防火墙 规则,则可能是由于 iptables 或 firewalld 服务未启用、规则为空或服务状态异常。以下是针对 iptables 与 firewalld 两种主流防火墙 工具 的基础配置说明:
一、确认当前使用的防火墙工具
Linux 发行版默认采用的防火墙管理工具可能不同:CentOS 7 及以后版本、RHEL 7+ 默认使用 firewalld;而较老系统或手动部署环境常直接使用 iptables。需先识别当前活跃的防火墙服务,避免规则冲突或重复配置。
1、执行命令 systemctl list-unit-files | grep -E “(iptables|firewalld)” 查看服务启用状态。
2、运行 systemctl status firewalld 和 systemctl status iptables 分别检查两者运行状态。
3、使用 iptables -L -n 查看当前 iptables 规则链是否为空或存在残留规则。
4、执行 firewall-cmd –state 判断 firewalld 是否正在运行。
二、iptables 基础规则配置
iptables 是基于内核 Netfilter 框架的命令行防火墙工具,通过定义链(INPUT、OUTPUT、FORWARD)和规则匹配数据包。所有规则按顺序逐条匹配,一旦命中即执行对应动作,后续规则不再处理。
1、清空现有规则:执行 iptables -F 清除所有链中的规则。
2、设置默认策略为 DROP:运行 iptables -P INPUT DROP、iptables -P FORWARD DROP、iptables -P OUTPUT DROP。
3、允许本地回环通信:输入 iptables -A INPUT -i lo -j ACCEPT。
4、允许已建立连接的响应流量:执行 iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT。
5、保存规则至开机生效:在 CentOS/RHEL 中使用 service iptables save;在 Debian/Ubuntu 中需安装 iptables-persistent 并运行 iptables-save > /etc/iptables/rules.v4。
三、firewalld 区域与服务配置
firewalld 采用动态管理模型,通过“区域(zone)”划分网络信任等级,并以“服务(service)”封装常用 端口 组合。默认区域为 public,适用于不可信网络环境。
1、启动并启用 firewalld 服务:执行 systemctl start firewalld 后立即运行 systemctl enable firewalld。
2、查看当前默认区域:运行 firewall-cmd –get-default-zone。
3、将 SSH 服务加入默认区域:输入 firewall-cmd –add-service=ssh –permanent。
4、开放自定义端口(如 8080):执行 firewall-cmd –add-port=8080/tcp –permanent。
5、重载配置使永久规则生效:运行 firewall-cmd –reload。
四、禁用 firewalld 并启用 iptables
若系统同时安装了 firewalld 与 iptables,且需统一使用 iptables 管理,必须先停用 firewalld 以防止其覆盖或干扰 iptables 规则。
1、停止 firewalld 服务:执行 systemctl stop firewalld。
2、禁用 firewalld 开机自启:运行 systemctl disable firewalld。
3、安装 iptables-services(RHEL/CentOS):使用 yum install iptables-services。
4、启动 iptables 服务:输入 systemctl start iptables。
5、启用 iptables 开机自启:执行 systemctl enable iptables。
五、验证防火墙规则生效情况
无论使用 iptables 还是 firewalld,均需通过实际连接测试验证规则是否按预期放行或拦截流量,避免因策略过于严格导致远程管理中断。
1、检查 iptables 当前规则列表:运行 iptables -L -n -v 查看各链匹配计数。
2、查询 firewalld 当前开放的服务:执行 firewall-cmd –list-services。
3、查看 firewalld 当前开放的端口:输入 firewall-cmd –list-ports。
4、从外部主机尝试 telnet 目标 IP 及关键端口(如 22、80):观察连接是否被拒绝或超时。
5、在服务器本地执行 ss -tuln | grep : 端口号 确认对应端口确有程序监听。