需先确认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 :端口号 确认对应端口确有程序监听。










