centos

centos iptables如何持久化保存

小樊
51
2025-04-30 16:42:16
栏目: 智能运维

在 CentOS 系统中,iptables 规则默认不会持久化保存。当系统重启时,之前设置的 iptables 规则会丢失。为了实现 iptables 规则的持久化保存,你可以使用以下方法:

方法一:使用 iptables-servicesfirewalld

  1. 安装 iptables-servicesfirewalld
sudo yum install iptables-services firewalld
  1. 启动 firewalld 服务并设置为开机启动:
sudo systemctl start firewalld
sudo systemctl enable firewalld
  1. 使用 firewall-cmd 命令添加防火墙规则。例如,允许 TCP 80 端口访问:
sudo firewall-cmd --permanent --zone=public --add-port=80/tcp
  1. 重新加载防火墙配置:
sudo firewall-cmd --reload
  1. 禁用 iptables 服务并停止:
sudo systemctl stop iptables
sudo systemctl disable iptables

现在,你的 iptables 规则已经持久化保存在 firewalld 配置中,系统重启后规则仍然有效。

方法二:手动保存和恢复 iptables 规则

  1. 保存当前的 iptables 规则到文件:
sudo iptables-save > /etc/sysconfig/iptables
  1. 创建一个脚本文件,例如 /etc/rc.d/rc.local,并在其中添加以下内容:
#!/bin/sh
#
# iptables-restore
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style func_init setup.
#
/path/to/iptables-restore < /etc/sysconfig/iptables
exit 0

确保将 /path/to/iptables-restore 替换为实际的 iptables-restore 命令路径(可以使用 which iptables-restore 查找)。

  1. 赋予脚本执行权限:
sudo chmod +x /etc/rc.d/rc.local
  1. 确保 /etc/rc.d/rc.local 在系统启动时执行。编辑 /etc/rc.d/rc.local 文件,确保以下行没有被注释掉:
/path/to/iptables-restore < /etc/sysconfig/iptables

现在,每次系统启动时,都会自动恢复之前保存的 iptables 规则。

0
看了该问题的人还看了