在 Ubuntu 上让 iptables 规则定时生效,常见有几种做法,取决于你是“定时启用/停用规则”还是“开机定时加载规则”。下面按场景说明。
cron(推荐)先保存一套规则:
iptables-save > /etc/iptables/iptables.rules
停用规则(清空):
iptables -F
iptables -X
iptables -Z
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
保存为:
/etc/iptables/iptables.flush
启用脚本 /usr/local/bin/iptables_on.sh:
#!/bin/bash
iptables-restore < /etc/iptables/iptables.rules
停用脚本 /usr/local/bin/iptables_off.sh:
#!/bin/bash
bash /etc/iptables/iptables.flush
赋予执行权限:
chmod +x /usr/local/bin/iptables_on.sh
chmod +x /usr/local/bin/iptables_off.sh
crontab -e
示例(每天 22:00 启用,08:00 停用):
0 22 * * * /usr/local/bin/iptables_on.sh
0 8 * * * /usr/local/bin/iptables_off.sh
iptables-persistentapt install iptables-persistent
保存规则:
iptables-save > /etc/iptables/rules.v4
开机自动加载(不是定时,但很常用)。
/etc/systemd/system/iptables-on.service
[Unit]
Description=Enable iptables rules
[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore /etc/iptables/iptables.rules
/etc/systemd/system/iptables-off.service
[Unit]
Description=Flush iptables rules
[Service]
Type=oneshot
ExecStart=/bin/bash /etc/iptables/iptables.flush
[Unit]
Description=Enable iptables at 22:00
[Timer]
OnCalendar=*-*-* 22:00:00
Persistent=true
[Install]
WantedBy=timers.target
同理创建 iptables-off.timer(08:00)
启用:
systemctl enable iptables-on.timer
systemctl enable iptables-off.timer
Ubuntu 20.04+ 默认用 nftables
iptables 可能是 nft 兼容层iptables -V
nf_tables,规则仍可用,但建议统一用 nft规则清空要小心
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
测试 cron/systemd 前先手动跑脚本
| 需求 | 推荐方式 |
|---|---|
| 简单定时开关 | cron |
| 系统级定时 | systemd timer |
| 开机生效 | iptables-persistent |
| 新系统 | 考虑 nftables |
如果你愿意,可以告诉我:
我可以直接帮你写完整脚本。