iptables规则持久化,启动配置

保存配置文件

sudo sh -c "iptables-save > /etc/iptables.rules"
使用该命令可以保存当前系统的iptables规则到特定文件。可以直接使用iptables-save > /etc/iptables.rules命令字串,但为了避免可能触发的重定向的权限问题,这里使用了-c选项,将这条字串变成一个整体的命令来执行。

方法一、/etc/network/interfaces

(注意:如果对该文件直接进行了错误的配置,可能会关闭或禁用所有的网络接口,导致你无法远程连接)
对该文件修改前,我们需要知道是对哪个网络接口进行配置。确定后,将相应的规则在相应的接口配置记录下面:
pre-up iptables-restore < /etc/iptables.rules
pre-up表示网卡启动前的动作
post-down iptables-restore < /etc/iptables.downrules
此外也可以配置相应的网卡关闭后的动作post-down,这里我们用不同的规则文件区分开来
完整的接口配置如下所示:

auto eth0
iface eth0 inet dhcp
  pre-up iptables-restore < /etc/iptables.rules
  post-down iptables-restore < /etc/iptables.downrules

(第一行‘auto’表示自动启动,‘inet dhcp’表示dhcp方式管理ip等参数设置)
sudo sh -c "iptables-save -c > /etc/iptables.rules"
此外,上述命令iptables-save 使用-c表示counter,即同时记录规则和网络收发的数据包的数量。

方法二、/etc/network/if-pre-up.d and ../if-post-down.d

在这两个文件夹中新建相应的脚本文件(文件名不能包含“·”)
新建/etc/network/if-pre-up.d/iptablesload

#!/bin/sh
iptables-restore < /etc/iptables.rules
exit 0

新建/etc/network/if-post-down.d/iptablessave

#!/bin/sh
iptables-save -c > /etc/iptables.rules
if [ -f /etc/iptables.downrules ]; then
   iptables-restore < /etc/iptables.downrules
fi
exit 0

之后我们还要确保脚本可执行
sudo chmod +x /etc/network/if-post-down.d/iptablessave
sudo chmod +x /etc/network/if-pre-up.d/iptablesload

方法三、使用iptables-persistent

sudo apt install iptables-persistent
安装完成后,使用netfilter-persistent命令管理

netfilter-persistent  uses  a  set of plugins to load, flush and save
netfilter rules at boot and halt time.  Plugins can be written in any
suitable language and stored in /usr/share/netfilter-persistent/plug‐
ins.d

将所想要保存的规则写入相应的rules.ipv4/rules.ipv6文件
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6
参考
http://manpages.ubuntu.com/manpages/bionic/man5/interfaces.5.html
https://help.ubuntu.com/community/IptablesHowTo

你可能感兴趣的:(iptables规则持久化,启动配置)