如何在Ubuntu 18上配置静态IP地址

本教程将向您展示在Ubuntu Linux上配置静态IP地址所需的所有步骤。

本教程在Ubuntu 18.04上进行了测试。

1.检测Linux上的网络接口

首先,您需要验证Ubuntu Linux是否检测到网络接口。

# lshw -C network

记下命名的网络接口逻辑。

在我们的示例中,系统检测到名为ENS160的网络接口。

*-network
description: Ethernet interface
product: VMXNET3 Ethernet Controller
vendor: VMware
physical id: 0
bus info: pci@0000:03:00.0
logical name: ens160
version: 01
serial: 00:0c:29:b1:46:b1
size: 10Gbit/s
capacity: 10Gbit/s
width: 32 bits
clock: 33MHz
capabilities: pm pciexpress msi msix bus_master cap_list rom ethernet physical logical tp 1000bt-fd 10000bt-fd
configuration: autonegotiation=off broadcast=yes driver=vmxnet3 driverversion=1.4.14.0-k-NAPI duplex=full ip=10.0.2.220 latency=0 link=yes multicast=yes port=twisted pair speed=10Gbit/s
resources: irq:18 memory:fd5fc000-fd5fcfff memory:fd5fd000-fd5fdfff memory:fd5fe000-fd5fffff ioport:4000(size=16) memory:fd500000-fd50ffff

2.备份网络配置文件

创建当前网络配置的备份。

# mkdir /backup
# cp /etc/netplan /backup -R

3.配置静态IP地址

访问Netplan目录并列出可用的配置文件。

# cd /etc/netplan
# ls

50-cloud-init.yaml

通常,您会找到名为01-netcfg.yaml的文件或名为50-cloud-init.yaml的文件。

在我们的示例中,假设您找到了一个名为50-cloud-init.yaml的文件。

编辑网络配置文件。

# cd /etc/netplan
# vi 50-cloud-init.yaml

以下是网络配置文件的默认内容:

Copy

这是我们配置的新文件。

Copy

在我们的示例中,网络接口ENS160配置为使用IP地址192.168.100.100/24,网关192.168.100.1和来自Google 8.8.8.8和8.8.4.4的DNS服务器。

Important!

The Netplan configuration files use the YAML configuration language

YAML is a human-friendly data serialization standard for all programming languages.
YAML is extremely sensitive to indentation errors.

启用新的网络配置。

# netplan generate
# netplan apply

4.验证网络配置

使用IFCONFIG命令验证网络接口配置。

# ifconfig

这是当前的网络接口配置。

ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.100.100 netmask 255.255.255.0 broadcast 192.168.255.255
inet6 fe80::20c:29ff:feb1:46b1 prefixlen 64 scopeid 0x20 ether 00:0c:29:b1:46:b1 txqueuelen 1000 (Ethernet)
RX packets 572572 bytes 258895818 (258.8 MB)
RX errors 0 dropped 319 overruns 0 frame 0
TX packets 132383 bytes 11603906 (11.6 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

验证DNS配置。

# systemd-resolve --status

这是当前的DNS配置。

Link 2 (ens160)
Current Scopes: DNS
LLMNR setting: yes
MulticastDNS setting: no
DNSSEC setting: no
DNSSEC supported: no
DNS Servers: 8.8.8.8
8.8.4.4

验证默认路由配置。

# netstat -nr

这是当前的路由表配置。

Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 192.168.100.1 0.0.0.0 UG 0 0 0 ens160
192.168.100.0 0.0.0.0 255.255.255.0 U 0 0 0 ens160