前言
在Ubuntu Server中,配置静态IP似乎变得“不太容易”,在官方从17版本引入了netplan之后,由于其使用了yaml的文件格式,在书写时要求格式,且字段还要完整。根据Ubuntu的官方文档描述:
netplan提供了一种高级的、与发行版无关的方法,用于定义如何通过YAML配置文件设置系统上的网络,它是一个涵盖网络配置所有方面配置的抽象层渲染器,如IP地址、网卡、DNS等。
在配置静态IP之前,需要先查看当前通过DHCP获取的IP信息,可以通过以下命令:
Bash
ip a
或者通过此命令可以查看网卡的硬件信息。
Bash
sudo lshw -class network
在输出的结果中,logical name: eth0
应该和ip a
的接口名称一致。
查看网卡接口信息
Bash
sudo ethtool eth0
ethtool是一个显示和更改网卡的程序,例如自动协商、端口速度、双模式和LAN唤醒。
它的工作目录在/etc/netplan/
下,默认情况下此目录为空或者只有一个50-cloud-init.yaml
文件,岂内容也是默认的使用DHCP配置类似于这样的内容:
YAML
network:
version: 2
ethernets:
eth0:
dhcp4: true
创建新的网络配置文件
建议使用一个新的配置文件来填写静态IP的信息,其文件的命名规则是以数字开头,中间加上有好的识别名称,比如01-static-ip.yaml。数字开头是一种执行的优先级。全部内容如下:
YAML
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: false
addresses:
- 10.10.10.2/24
routes:
- to: default
via: 10.10.10.1
nameservers:
addresses:
- 10.10.10.253
- 8.8.8.8
设置权限为600
Bash
sudo chmod 600 01-static-ip.yaml
使用try命令来确保语法没有错误,并且如果在2分钟内没有按键确认,配置不会生效(自动回滚)
Bash
sudo netplan try --debug
确认无误之后,执行应用命令。推荐加上--debug
参数来查看执行过程。
Bash
sudo netplan apply
通过get命令来确保已经生效。
Bash
sudo netplan get
如果在输出的结果中显示dhcp4: true
,并且ip a的结果中同样显示dhcp还在生效,则需要关闭50-cloud-init.yaml
中的dhcp4: true
为false
。
NetPlan常用命令
输入help命令可以查看常用的几个命令
Bash
sudo netplan help
# 输出
usage: /usr/sbin/netplan [-h] [--debug] ...
Network configuration in YAML
options:
-h, --help show this help message and exit
--debug Enable debug messages
Available commands:
help Show this help message # 显示帮助信息
apply Apply current netplan config to running system # 应用当前配置到整个系统
generate Generate backend specific configuration files from /etc/netplan/*.yaml # 生成配置文件
get Get a setting by specifying a nested key like "ethernets.eth0.addresses", or "all" # 显示配置信息,如只显示IP地址或者全部
info Show available features # 显示当前可用的特性
ip Retrieve IP information from the system
set Add new setting by specifying a dotted key=value pair like ethernets.eth0.dhcp4=true # 采用键值对的方式进行设置,如关闭DHCP4。
rebind Rebind SR-IOV virtual functions of given physical functions to their driver # 重新绑定虚拟化网卡和物理网卡之间的关系
status Query networking state of the running system # 显示当前运行状态
try Try to apply a new netplan config to running system, with automatic rollback # 带自动回滚的应用功能,(建议在尝试新的配置文件之前进行操作。)