温馨提示×

centos怎么导入防火墙规则

小樊
44
2026-10-26 21:26:09
栏目: 智能运维

在 CentOS 中,“导入防火墙规则”通常分为两种情况:

  1. 使用 firewalld(CentOS 7 及以后默认)
  2. 使用 iptables(传统方式)

下面分别说明。


一、CentOS 7/8/Stream(firewalld 方式)

1️⃣ 从文件导入 firewalld 规则

firewalld 支持直接加载配置文件。

方法一:使用 .xml 规则文件

firewalld 规则通常以 XML 形式存在:

/etc/firewalld/zones/public.xml

导入步骤:

# 停止 firewalld(可选)
systemctl stop firewalld

# 将规则文件放到对应目录
cp public.xml /etc/firewalld/zones/

# 重新加载
systemctl start firewalld
firewall-cmd --reload

方法二:使用 firewall-cmd 批量导入

如果你有一个脚本或命令清单:

firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --permanent --add-service=http
firewall-cmd --reload

2️⃣ 从 iptables-save 文件转换为 firewalld(不推荐)

firewalld 不直接支持 iptables-save 文件导入,需要手动转换。


二、CentOS 6 或手动使用 iptables

1️⃣ 导入 iptables 规则文件

如果你有一个规则文件(如 iptables.rules):

iptables-restore < iptables.rules

查看是否生效:

iptables -L -n

2️⃣ 开机自动导入

# 保存当前规则
service iptables save

# 或
iptables-save > /etc/sysconfig/iptables

确保服务开机启动:

chkconfig iptables on

三、常见示例

示例:导入端口规则

firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload

示例:导入富规则

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" accept'
firewall-cmd --reload

四、注意事项

  • CentOS 7+ 默认是 firewalld,不是 iptables
  • 不要同时启用 firewalld 和 iptables
  • 修改规则后一定要 --reload

如果你有具体的规则文件内容(iptables 或 firewalld),可以贴出来,我可以帮你转换成对应格式。

0 踩