修复Linux中的'sudo:无法解析主机'错误

时间:2020-03-05 15:29:48  来源:igfitidea点击:

我在Ubuntu 18.04服务器创建了一个sudo用户,因为我不希望一直都是root用户,特别是在修补系统时。

当我开始在sudo中使用命令时,我在命令的输出中看到一个奇怪的错误:

sudo: unable to resolve host test-server

该命令以sudo运行,没有任何问题,但是无论如何都会显示此错误消息。

修复sudo:无法解析主机

该错误的根本原因实际上与主机名更改有关。
让我向我们展示如何解决无法解析的主机名错误。

首先,使用hostname命令检查系统的主机名。
在我的情况下,主机名是test-server。

$hostname
test-server

主机名取自/etc/hostname文件。

cat /etc/hostname 
test-server

同样的主机名也应该在/etc/hosts文件中列出。
但是在我的情况下(我猜也是在情况下),/etc/hosts文件中缺少此主机名,如下面的输出所示:

127.0.0.1 localhost
The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

由于此处缺少它,因此系统无法确定主机名,因此会引发错误“ sudo:无法解析主机”。

要解决此问题,请编辑该文件并添加新行,并使用主机名设置回送地址。
我们可以使用Vim在命令行中编辑文件。

127.0.0.1 <hostname>

所以现在,我的/etc/hosts文件看起来像这样:

127.0.0.1 localhost
127.0.0.1 test-server
The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

提示:如果/etc/hosts文件中的任何位置仍然存在旧主机名,则应将其替换为新主机名。

添加上述行后,“ sudo:无法解析主机”错误立即消失。