Ubuntu 上设置 iptables 规则开机自启

在 Ubuntu 上设置 iptables 规则开机自启,可以通过以下方法实现:

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

Ubuntu 服务器上 iptables 规则不会自动保存,因此需要 iptables-persistent 来持久化规则并在开机时自动加载。

  1. 安装 iptables-persistent
    sudo apt update
    sudo apt install iptables-persistent -y
    安装过程中会要求保存当前的 iptables 规则,选择 Yes。
  2. 保存 iptables 规则
    如果你已经配置了 iptables 规则,可以手动保存:
    sudo netfilter-persistent save
    或者:
    sudo iptables-save > /etc/iptables/rules.v4
    sudo ip6tables-save > /etc/iptables/rules.v6 # 如果使用 IPv6
  3. 重新加载 iptables 规则
    sudo netfilter-persistent reload
  4. 确保 iptables-persistent 在开机时运行
    sudo systemctl enable netfilter-persistent
    sudo systemctl start netfilter-persistent

方法 2:使用 rc.local(适用于较旧版本的 Ubuntu)

如果你不想使用 iptables-persistent,可以在 /etc/rc.local 中添加规则。

  1. 编辑 /etc/rc.local
    sudo nano /etc/rc.local
    在 exit 0 之前添加:
    iptables-restore < /etc/iptables/rules.v4
    如果使用 IPv6:
    ip6tables-restore < /etc/iptables/rules.v6
    然后保存并退出(Ctrl + X,然后按 Y)。
  2. 赋予执行权限
    sudo chmod +x /etc/rc.local
  3. 让 rc.local 生效
    如果 /etc/rc.local 不存在,可以手动创建并启用:
    sudo touch /etc/rc.local
    sudo chmod +x /etc/rc.local
    sudo systemctl enable rc-local
    sudo systemctl start rc-local

方法 3:使用 systemd 自定义服务

你可以创建一个 systemd 服务来在启动时恢复 iptables 规则。

  1. 创建 iptables 服务
    sudo nano /etc/systemd/system/iptables.service
    添加以下内容:

    Unit

    Description=Restore iptables rules
    After=network.target

Service

Type=oneshot

ExecStart=/sbin/iptables-restore < /etc/iptables/rules.v4

ExecStart=/sbin/ip6tables-restore < /etc/iptables/rules.v6

RemainAfterExit=yes

Install

WantedBy=multi-user.target

  1. 重新加载 systemd 并启用服务

sudo systemctl daemon-reload

sudo systemctl enable iptables

sudo systemctl start iptables

验证 iptables 规则是否生效

sudo iptables -L -v -n

如果重启后 iptables 规则仍然存在,则说明设置成功。

如果你是用于生产环境,建议使用 方法 1(iptables-persistent),因为它是 Ubuntu 官方推荐的方法,并且管理方便。

相关推荐
GeW4 分钟前
以Linux为基、数据库为核:新质生产力路线图下的企业架构升级
linux
云边云科技_云网融合11 分钟前
从 POS 机到访客 Wi-Fi:零售门店安全建设的完整解法
服务器·网络·数据库
忆挽篱笙歌19 分钟前
进程的状态
linux·ubuntu
kyle~36 分钟前
Linux --- Socket 用户进程与内核网络协议栈之间的统一接口
linux·arm开发·网络协议
hiahiahia12342 分钟前
Message 和对话
服务器·前端·数据库
重生之小比特1 小时前
【Linux系统】07 进程状态
linux·运维·服务器
土星云SaturnCloud1 小时前
土星云边缘计算+AI视觉+视频存管:连锁汽修数字化升级实践
服务器·人工智能·ai·边缘计算
张洛闻Eren2 小时前
Ansible【第二课】:实施 Ansible Playbook
linux·运维·服务器·云原生·kubernetes·k8s·ansible
启博网络2 小时前
启博安企服务器与ERP加速服务器如何区分?一文讲透
运维·服务器
Zhu7582 小时前
【开源脚本】Ubuntu环境下载任意软件
linux·运维·ubuntu