在 CentOS 系统中,查看 iptables 防火墙规则的方法取决于你的 CentOS 版本以及当前系统的防火墙管理方式。
以下是几种常见的方法:
无论 CentOS 版本如何,只要 iptables 服务正在运行,都可以使用以下命令:
查看所有表的规则(推荐):
iptables -L -n -v
-L: 列出规则 (List)。-n: 以数字形式显示 IP 地址和端口(不进行 DNS 反向解析,速度更快)。-v: 显示详细信息(如数据包计数、字节数)。查看指定表(如 nat 表)的规则:
默认查看的是 filter 表。如果你想查看 NAT 规则,需要指定 -t nat:
iptables -t nat -L -n -v
查看规则并显示规则编号(行号):
如果你打算删除某条规则,加上 --line-numbers 会非常有用:
iptables -L -n -v --line-numbers
在 CentOS 6 中,iptables 是默认的防火墙服务。
查看服务状态:
service iptables status
注意:这个命令在 CentOS 6 中会打印出当前的规则列表。
保存的配置文件位置:
规则通常保存在 /etc/sysconfig/iptables 文件中,你可以直接查看文件内容:
cat /etc/sysconfig/iptables
关键点: CentOS 7 默认使用 firewalld 作为防火墙管理工具,iptables 服务默认可能未安装或未启用。如果你直接运行 iptables -L,可能会看到全是空的(除了默认链),或者提示命令不存在。
请按以下步骤排查:
如果你想查看防火墙规则,但系统用的是 firewalld,你应该使用 firewall 命令,或者查看 firewalld 底层调用的 iptables 规则。
查看 firewalld 状态:
systemctl status firewalld
查看 firewalld 当前的规则(类似于 iptables 的输出):
iptables -L -n
注意:即使启用了 firewalld,iptables 命令通常依然存在,它显示的是内核中 netfilter 的规则,这些规则正是由 firewalld 生成的。
如果你在 CentOS 7 上卸载了 firewalld 并安装回了传统的 iptables-services,你需要先确保服务在运行。
检查 iptables 服务状态:
systemctl status iptables
如果提示 “Unit iptables.service could not be found”: 说明你没有安装传统的 iptables 服务,你需要先安装它(如果你确实想用传统配置):
yum install iptables-services
systemctl stop firewalld
systemctl disable firewalld
systemctl start iptables
systemctl enable iptables
安装并启动后,再使用 iptables -L -n -v 查看。
iptables 有四张表(Table):filter(过滤)、nat(地址转换)、mangle(修改数据包)、raw。
你可以分别查看它们:
iptables -t filter -L -n
iptables -t nat -L -n
iptables -t mangle -L -n
最常用的一行命令,查看所有详细信息(包括协议、源目地址、端口):
sudo iptables -t filter -L -n -v --line-numbers
注意: 如果是 CentOS 7/8 且正在使用 firewalld,直接修改 iptables 规则可能会与 firewalld 冲突,建议要么使用 firewall-cmd 管理,要么彻底切换到 iptables-services。