Ubuntu 服务器上设置固定IP

Ubuntu 17.10之后版本

从 Ubuntu 17.10 及更高版本开始,网络由Netplan功能控制。Netplan的配置文件位于该目录中,并以 YAML 编写。在此目录中,您将找到标记为或的YAML 配置文件。 

/etc/netplan50-cloud-init.yaml 或 00-installer-config.yaml

如果您正在运行的Ubuntu是云实例,它很可能由cloud-init管理,它通过利用 DHCP 协议自动为其分配 IP 地址。那我们需要先禁用 cloud-init。编辑/etc/cloud/cloud.cfg.d/目录中的 subiquity-disable-cloudinit-networking.cfg

$ sudo vi /etc/cloud/cloud.cfg.d/subiquity-disable-cloudinit-networking.cfg

将“网络”设置为“禁用”。

network: {config: disabled}

保存更改并退出。

接下来,编辑Netplan配置文件。我的是00-installer-config.yaml文件。

$ sudo vi /etc/netplan/00-installer-config.yaml

从配置文件中,我们修改“network”, 其中“ ethernets ”指定网络接口,“version”是渲染器的版本

我们要将“ dhcp4 ”值设为“ no ”以禁用 DHCP 协议并指定接口的静态 IP,如下所示。

要为 ens3 接口分配静态 IP 地址,请按如下方式修改文件:

  • 指定服务器的静态 IP 地址。在  addresses: 部分中,指定要分配给网络接口的 IPv4 地址。
  • 接下来,指定网关。
  • 再下面的 nameservers,指定名称服务器的 DNS 或 IP 地址。在这里,我们指定了 Google 的 DNS 8.8.8.8 和路由器的 IP。
network:
   ethernets:
        enp0s3:
            dhcp4: no
            addresses: [192.168.2.150/24]
            gateway4: 192.168.2.1
            nameservers:
                               addresses: [8.8.8.8, 192.168.2.1]

保存 YAML 文件并退出。要应用所做的更改,请运行以下命令:

$ sudo netplan apply

您可以使用 ifconfig 或 ip 命令来验证您的网络接口是否设置为使用刚才配置的静态 IP。

此外,您可以使用 IP route show 命令显示系统上的新路由。

$  ip route show

完美!

Ubuntu 17.10 及之前版本

Let’s open up the /etc/network/interfaces file. I’m going to use vi, but you can choose a different editor

sudo vi /etc/network/interfaces

For the primary interface, which is usually eth0, you will see these lines:

auto eth0
iface eth0 inet dhcp

As you can see, it’s using DHCP right now. We are going to change dhcp to static, and then there are a number of options that should be added below it. Obviously you’d customize this to your network.

auto eth0
iface eth0 inet static
        address 192.168.1.200
        netmask 255.255.255.0
        network 192.168.1.0
        broadcast 192.168.1.255
        gateway 192.168.1.1

Now we’ll need to add in the DNS settings by editing the resolv.conf file:

sudo vi /etc/resolv.conf

On the line ‘name server xxx.xxx.xxx.xxx’ replace the x with the IP of your name server. (You can do ifconfig /all to find out what they are)

Now we’ll just need to restart the networking components:

sudo /etc/init.d/networking restart

Ping www.baidu.com. If you get a response, name resolution is working(unless of course if google is in your hosts file).

So easy 对吧!

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注