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 官方推荐的方法,并且管理方便。

相关推荐
南瓜胖胖22 分钟前
【seismic unix相速度分析-频散曲线】
服务器·unix
热爱生活的猴子3 小时前
阿里云服务器正确配置 Docker 国内镜像的方法
服务器·阿里云·docker
物联网老王5 小时前
Ubuntu Linux Cursor 安装与使用一
linux·运维·ubuntu
一位摩羯座DBA7 小时前
Redhat&Centos挂载镜像
linux·运维·centos
学习3人组7 小时前
CentOS配置网络
linux·网络·centos
计算机毕设定制辅导-无忧学长8 小时前
西门子 PLC 与 Modbus 集成:S7-1500 RTU/TCP 配置指南(一)
服务器·数据库·tcp/ip
weixin_307779138 小时前
Hive集群之间迁移的Linux Shell脚本
大数据·linux·hive·bash·迁移学习
漫步企鹅8 小时前
【蓝牙】Linux Qt4查看已经配对的蓝牙信息
linux·qt·蓝牙·配对
cui_win9 小时前
【网络】Linux 内核优化实战 - net.core.flow_limit_table_len
linux·运维·网络
梦在深巷、9 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb