温馨提示×

debian iptables怎么开机自启

小樊
41
2026-10-22 04:58:30
栏目: 智能运维

在 Debian 中,iptables 本身不是“服务”,所以不能直接用 systemctl enable iptables 来开机自启(新版本 Debian 默认也没有 iptables 服务)。常见做法是:开机时自动恢复保存好的 iptables 规则。

下面给你几种常用、可靠的方法。


方法一(推荐):使用 iptables-persistent

1. 安装

sudo apt update
sudo apt install iptables-persistent

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

  • 选 Yes 即可

2. 保存规则(以后修改规则后)

sudo netfilter-persistent save

3. 开机自动恢复

Debian 会自动启用:

systemctl status netfilter-persistent

重启后规则会自动加载。


方法二:用 systemd 自定义服务(更可控)

1. 保存当前规则

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

(目录不存在就自己建)

2. 创建 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

3. 启用

sudo systemctl enable iptables-restore

方法三(老系统):rc.local

如果你用的是老 Debian 且有 rc.local:

iptables-restore < /etc/iptables/rules.v4

加到 /etc/rc.local 的 exit 0 前。


注意事项

  • Debian 新版本默认用 nftables
  • 如果你看到 nft list ruleset 有内容,说明系统在用 nftables
  • 可用:
    update-alternatives --config iptables
    
    切换为 iptables-legacy

如果你愿意,可以告诉我:

  • Debian 版本(cat /etc/debian_version)
  • 是否用 nftables
  • 是服务器还是桌面

我可以给你最合适的一套配置。

0 踩