温馨提示×

ubuntu iptables如何定时生效

小樊
55
2026-10-01 01:42:02
栏目: 智能运维

在 Ubuntu 上让 iptables 规则定时生效,常见有几种做法,取决于你是“定时启用/停用规则”还是“开机定时加载规则”。下面按场景说明。


一、定时启用 / 停用 iptables 规则(最常见)

方法 1:使用 cron(推荐)

1. 准备规则文件

先保存一套规则:

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

2. 编写脚本

启用脚本 /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

3. 配置 cron

crontab -e

示例(每天 22:00 启用,08:00 停用):

0 22 * * * /usr/local/bin/iptables_on.sh
0 8  * * * /usr/local/bin/iptables_off.sh

二、开机自动生效(但不是“定时”)

方法 2:使用 iptables-persistent

apt install iptables-persistent

保存规则:

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

开机自动加载(不是定时,但很常用)。


三、使用 systemd timer(更“现代”)

1. 创建 service

/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

2. 创建 timer

[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

四、注意事项(很重要)

  1. Ubuntu 20.04+ 默认用 nftables

    • iptables 可能是 nft 兼容层
    • 查看:
      iptables -V
      
    • 若显示 nf_tables,规则仍可用,但建议统一用 nft
  2. 规则清空要小心

    • 远程服务器别把自己踢出 SSH
    • 建议保留:
      iptables -A INPUT -p tcp --dport 22 -j ACCEPT
      
  3. 测试 cron/systemd 前先手动跑脚本


五、总结建议

需求 推荐方式
简单定时开关 cron
系统级定时 systemd timer
开机生效 iptables-persistent
新系统 考虑 nftables

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

  • Ubuntu 版本
  • 是服务器还是本地
  • 想“几点开、几点关”

我可以直接帮你写完整脚本。

0 踩