温馨提示×

ubuntu iptables如何开机

小樊
53
2026-10-03 22:55:04
栏目: 智能运维

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


一、使用 iptables-persistent(最推荐 ✅)

1. 安装

sudo apt update
sudo apt install iptables-persistent

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

  • 选 Yes 即可

2. 保存当前规则

sudo netfilter-persistent save

或

sudo iptables-save > /etc/iptables/rules.v4

3. 开机自动加载

iptables-persistent 会在开机时自动加载:

/etc/iptables/rules.v4

查看状态

sudo netfilter-persistent status

二、使用 systemd 服务(手动方式)

如果你不想装 iptables-persistent:

1. 保存规则

sudo iptables-save > /etc/iptables.rules

2. 创建 systemd 服务

sudo vim /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
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

3. 启用

sudo systemctl enable iptables-restore

三、写到 /etc/rc.local(不推荐 ⚠️)

仅旧系统或特殊环境使用:

sudo vim /etc/rc.local

添加:

iptables-restore < /etc/iptables.rules

并确保:

chmod +x /etc/rc.local

四、IPv6 规则(如需要)

sudo ip6tables-save > /etc/iptables/rules.v6

总结建议

✅ 最佳实践:

apt install iptables-persistent
netfilter-persistent save

如果你使用的是 Ubuntu 20.04+ / 22.04+,并且是新服务器,也可以考虑直接用 nftables(未来趋势)。

需要我帮你写一份完整的 iptables 开机规则示例吗?

0 踩