如何在 Ubuntu Server 中设置静态路由?

如何在 Ubuntu Server 中设置静态路由?

我从 Ubuntu 8.10 开始使用 Ubuntu;现在我正在使用 Ubuntu 12.04 Server。

我在启动时很难保持静态路由。我通常会将路由命令

/sbin/route add -net <IP>/<MASK> <GW> dev <ethX>

或者我会在目录内/etc/rc.local创建一个文件(名为) ,但我注意到在 Ubuntu 12.04 上它不起作用。 routes/etc/network/if-up/

如果我在 shell 中输入命令,它们会起作用,但是当它们位于指定的文件中时,相同的命令不起作用。

我已经尝试将文件名更改为其他名称,认为我的文件名(routes)在 Ubuntu 12.04 中可能有误,但这也不起作用。

我还注意到该命令/sbin/ifconfig有效,但少了/sbin/route

网络设置发生了什么变化?

如何在 Ubuntu 12.04 上定义静态路由?

答案1

您可以将静态路由放入/etc/network/interfaces

auto eth0
iface eth0 inet static
      address 192.168.1.2
      netmask 255.255.255.0
      up route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1
      up route add -net 172.16.0.0 netmask 255.240.0.0 gw 192.168.1.1

答案2

我经常发现定义静态路由的正确位置是在 /etc/network/interfaces 中,例如,如果您要使用 /etc/init.d/networking restart 全局重新启动网络,则这样做是可以的。但是,如果您要使用 ifdown 和 ifup 单独关闭接口,ifup 将以以下错误结束:

ifup eth1

RTNETLINK answers: File exists
Failed to bring up eth1.

因为它尝试定义一条路由,但该路由已经定义。接口无论如何都会启动,但 ifup 不会更新 /run/network/ifstate,因此下次使用 ifdown 时,除非使用 --force 标志,否则您将无法执行此操作。

为了让 ifup 在路由已经定义的情况下继续配置,你可以在 /etc/network/interfaces 中定义路由时使用这种格式

up ip route add 172.16.0.0/24 via 192.168.10.1 || true
up ip route add 192.168.0.0/16 via 192.168.10.1 || true

这样,您将在输出中看到警告,但接口配置将完成

ifup eth1

RTNETLINK answers: File exists
RTNETLINK answers: File exists
ssh stop/waiting
ssh start/running, process 18553

答案3

由于它是 2021 年,您可以netplan在 ubuntu 18.04 或更高版本上对其进行配置(在 ubuntu 20.04 上测试)。 完整参考资料可参见netplan 网站/etc/netplan/. 配置文件可以在目录下找到。

network:
  version: 2
  ethernets:
    ens160: # in my case the interface name is ens160
      dhcp4: false  # or true. depends on your situation
      addresses: [192.168.0.10/24]  # your static IP address
      # the actual answer is here
      routes:
        - to: 0.0.0.0/0  # or any other subnet you like. 0.0.0.0/0 means default gateway
          via: 172.16.0.1  # or any other gateway you want.
          on-link: true   # as you see my interface IP address and default gateway are not in the same subnet so we should put this true but if they are in the same subnet this is not required. 

PS. YAML 配置文件对缩进很敏感,并且不接受制表符。缩进是 2 个空格。

别忘了跑netplan apply

答案4

有一个包ifupdown-额外在 Ubuntu 中可用。
它提供了自动脚本(安装在/etc/network/*/),其中一个用于添加静态路由。

其配置文件是 /etc/network/routes

这个配置文件的顶部有一个很好的描述:

该配置文件由 static-routes if-updown 脚本和 /etc/init.d/networking-routes 脚本读取,以设置与给定接口或全局路由相关的路由列表。

我使用的路线示例是:

192.168.240.0 255.255.255.0 192.168.130.3 em3

相关内容