温馨提示×

ubuntu iptables怎么开机启动

小樊
46
2026-09-19 02:29:09
栏目: 智能运维

在 Ubuntu 上让 iptables 规则开机自动生效,常见做法有以下几种(按推荐程度排序):


一、推荐方式(Ubuntu 20.04+):使用 netfilter-persistent

1. 安装工具

sudo apt update
sudo apt install iptables-persistent

安装过程中会问你是否保存当前规则,选 Yes

2. 保存当前 iptables 规则

sudo netfilter-persistent save

规则会保存到:

  • /etc/iptables/rules.v4(IPv4)
  • /etc/iptables/rules.v6(IPv6)

3. 设置开机启动

sudo systemctl enable netfilter-persistent

以后修改规则后,只需:

sudo netfilter-persistent save

二、旧方式(不推荐):rc.local

如果你用的是老版本 Ubuntu:

sudo nano /etc/rc.local

在 exit 0 前加入:

iptables-restore < /etc/iptables.rules

并赋予执行权限:

sudo chmod +x /etc/rc.local

三、使用 systemd 服务(进阶)

创建服务文件:

sudo nano /etc/systemd/system/iptables-restore.service

内容:

[Unit]
Description=Restore iptables rules
Before=network-pre.target
Wants=network-pre.target

[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore /etc/iptables/rules.v4
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

启用:

sudo systemctl enable iptables-restore

四、查看当前规则

sudo iptables -L -n -v

✅ 总结

方法 推荐度
netfilter-persistent ⭐⭐⭐⭐⭐
systemd 自定义服务 ⭐⭐⭐⭐
rc.local ⭐⭐

如果你告诉我 Ubuntu 版本 或 用的是 nftables 还是 iptables,我可以给你更精确的步骤。

0 踩