前要

Ubuntu 22.04 上默认网络管理工具是Netplan

DNS 配置文件的位置在 /etc/resolv.conf 文件,但是文件第一行就提到了是自动生成的,不要编辑

# This file is managed by man:systemd-resolved(8). Do not edit.

Netplan配置文件在 /etc/netplan 目录,通常该文件名为01-netcfg.yaml(名字无所谓,但是肯定是 .yaml 结尾的文件)。

配置无线和DNS

我们可以通过编辑 01-netcfg.yaml 文件来配置指定的DNS和无线网络

可以通过 ifconfig 命令先查看自己的网卡信息

1
ifconfig

eg:

  • enp2s0 是我的有线网卡名
  • wlo1 是我的无线网卡名

相关命令:

1
2
3
4
5
6
7
8
#打开使用中的网卡
ifconfig 网卡名 up

#关闭使用中的网卡
ifconfig 网卡名 down

#更改当前的IP地址
ifconfig 网卡名 IP地址

确定并记录自己的无线网卡名

1
vim /etc/netplan/01-netcfg.yaml

无线部分的配置文件(yaml格式要注意缩进!)

1
2
3
4
5
6
7
8
network:
wifis:
wlo1:
access-points:
wifi name:
password: wifi password
dhcp4: true
version: 2

DNS部分的配置

1
2
nameservers:
addresses: [223.5.5.5]

无线和有线的配置文件放到一起(注意 enp2s0wlo1 分别是我的有线网卡名和无线网卡名)

1
2
3
4
5
6
7
8
9
10
11
12
13
network:
ethernets:
enp2s0:
dhcp4: true
wifis:
wlo1:
dhcp4: true
nameservers:
addresses: [223.5.5.5, 8.8.8.8]
access-points:
wifi name:
password: wifi password
version: 2

配置完成以后检查一下配置文件格式有没有问题,执行以下命令

1
netplan generate

如果没有任何信息输出,则没有问题

运行命令,应用更改

1
netplan apply

此时,Netplan将为 systemd-resolved 的服务生成配置文件 /run/systemd/resolve/resolv.conf

创建软连接

如果此时还有一些应用程序依然使用 /etc/resolv.conf 的配置文件的DNS地址进行域名的解释,因此还需要修改 /etc/resolv.conf 文件

要修改此文件我们只需要将 /run/systemd/resolve/resolv.conf 软链接到 /etc/resolv.conf 即可

运行命令

1
ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf

验证

1
nslookup baidu.com

ShiGuang@ubuntu:~$ nslookup baidu.com
Server: 127.0.0.53
Address: 127.0.0.53#53

Non-authoritative answer:
Name: baidu.com
Address: 110.242.68.66
Name: baidu.com
Address: 39.156.66.10

“Server”行指示使用的DNS服务器,而“Address”行指示找到的IP地址。

如果这两行中的IP地址与您在DNS更改中指定的IP地址匹配,则表示DNS更改已成功生效。