Некоторые пользователи сталкиваются с ошибкой «sudo unable to resolve host». Обычно, эта ошибка появляется после смены имени компьютера. Это простая проблема, которую можно быстро решить.
В этой статье мы рассмотрим, почему возникает эта ошибка, что она означает, а также как её решить на примере Ubuntu.
Сообщение «unable to resolve host имя_хоста» означает, что утилита не может определить IP-адрес хоста «имя_хоста«. Казалось бы, sudo — это локальная команда для повышения привилегий в системе, и ей незачем определять IP хостов. Но это не совсем так: sudo может использоваться и удалёнными пользователями, например, подключёнными по SSH, а в самом конфигурационном файле /etc/sudoers уровни доступа различных пользователей настраиваются такой строчкой:
пользователь хост=(другой_пользователь:группа) команды
Подробнее про строку настройки читайте в статье настройка sudo в linux. А сейчас нам интересно, что для каждого запроса утилите нужно определить, какой хост используется на данном компьютере.
Если кратко, то основная идея разработчиков состоит в том, что один универсальный файл /etc/sudoers будет использоваться на множестве компьютеров и на каждом из них нужно определить, какие правила предназначены для него. Таким образом, переменная host в sudoers влияет только на локальные правила.
А теперь вернёмся к нашей ошибке. Как я уже сказал, она означает, что утилита не может определить IP-адрес «имени хоста». Для домена сайта это означало бы, что такой записи нет в DNS. Но поскольку это имя нашего локального компьютера, то вполне естественно, что его нет в глобальной сети.
Как исправить ошибку
1. Решение проблемы в /etc/hosts
Чтобы исправить ошибку, мы можем добавить такую DNS-запись локально в файл /etc/hosts. Поскольку sudo у вас не работает, а этот файл можно редактировать только от суперпользователя, то эта простая задача становится сложнее. Сначала смотрим наше текущее имя хоста:
hostname
Дальше, если у вас установлен пароль root, вы можете авторизоваться от его имени с помощью su:
su -
А затем добавить такую строчку в /etc/hosts:
vi /etc/hosts
127.0.0.1 имя_хоста
Слова «имя_хоста» надо заменить на то имя хоста, которое вы получили с помощью команды hostname. После этого надо перезапустить компьютер или просто перезапустить сеть:
sudo systemctl restart networking
Ещё желательно убедиться, что в системной службе разрешения доменных имён включено использование файла /hosts. Откройте /etc/nsswitch.conf и найдите в строке hosts слово «files». Оно должно быть на первом месте. Если нет, перенесите его на первое место.
Если же у вас пароль для root не установлен, вам нужно загрузиться с LiveCD, примонтировать корневую файловую систему в /mnt/ и исправлять ошибку уже там.
2. Решение с помощью systemd
Есть ещё один путь. В попытках воспроизвести эту проблему в своей Ubuntu 18.04 я обнаружил, что разрешением доменных имён для локальных приложений занимается служба systemd-resolved. Если она запущена, то даже если в файле /etc/hosts нет имени вашего компьютера, всё будет работать. Поэтому, если вы случайно отключили эту службу, верните её на место и всё заработает:
sudo systemctl start systemd-resolved
sudo systemctl enable systemd-resolved
Выводы
В этой статье мы разобрали, как справиться с ошибкой «sudo cannot to resolve host». Как видите, всё достаточно логично и просто. Если у вас остались вопросы, спрашивайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
Некоторые пользователи сталкиваются с ошибкой «sudo unable to resolve host». Обычно, эта ошибка появляется после смены имени компьютера. Это простая проблема, которую можно быстро решить.
В этой статье мы рассмотрим, почему возникает эта ошибка, что она означает, а также как её решить на примере Ubuntu.
Сообщение «unable to resolve host имя_хоста» означает, что утилита не может определить IP-адрес хоста «имя_хоста«. Казалось бы, sudo — это локальная команда для повышения привилегий в системе, и ей незачем определять IP хостов. Но это не совсем так: sudo может использоваться и удалёнными пользователями, например, подключёнными по SSH, а в самом конфигурационном файле /etc/sudoers уровни доступа различных пользователей настраиваются такой строчкой:
пользователь хост=(другой_пользователь:группа) команды
Подробнее про строку настройки читайте в статье настройка sudo в linux. А сейчас нам интересно, что для каждого запроса утилите нужно определить, какой хост используется на данном компьютере.
Если кратко, то основная идея разработчиков состоит в том, что один универсальный файл /etc/sudoers будет использоваться на множестве компьютеров и на каждом из них нужно определить, какие правила предназначены для него. Таким образом, переменная host в sudoers влияет только на локальные правила.
А теперь вернёмся к нашей ошибке. Как я уже сказал, она означает, что утилита не может определить IP-адрес «имени хоста». Для домена сайта это означало бы, что такой записи нет в DNS. Но поскольку это имя нашего локального компьютера, то вполне естественно, что его нет в глобальной сети.
Как исправить ошибку
1. Решение проблемы в /etc/hosts
Чтобы исправить ошибку, мы можем добавить такую DNS-запись локально в файл /etc/hosts. Поскольку sudo у вас не работает, а этот файл можно редактировать только от суперпользователя, то эта простая задача становится сложнее. Сначала смотрим наше текущее имя хоста:
hostname
Дальше, если у вас установлен пароль root, вы можете авторизоваться от его имени с помощью su:
su -
А затем добавить такую строчку в /etc/hosts:
vi /etc/hosts
127.0.0.1 имя_хоста
Слова «имя_хоста» надо заменить на то имя хоста, которое вы получили с помощью команды hostname. После этого надо перезапустить компьютер или просто перезапустить сеть:
sudo systemctl restart networking
Ещё желательно убедиться, что в системной службе разрешения доменных имён включено использование файла /hosts. Откройте /etc/nsswitch.conf и найдите в строке hosts слово «files». Оно должно быть на первом месте. Если нет, перенесите его на первое место.
Если же у вас пароль для root не установлен, вам нужно загрузиться с LiveCD, примонтировать корневую файловую систему в /mnt/ и исправлять ошибку уже там.
2. Решение с помощью systemd
Есть ещё один путь. В попытках воспроизвести эту проблему в своей Ubuntu 18.04 я обнаружил, что разрешением доменных имён для локальных приложений занимается служба systemd-resolved. Если она запущена, то даже если в файле /etc/hosts нет имени вашего компьютера, всё будет работать. Поэтому, если вы случайно отключили эту службу, верните её на место и всё заработает:
sudo systemctl start systemd-resolved
sudo systemctl enable systemd-resolved
Выводы
В этой статье мы разобрали, как справиться с ошибкой «sudo cannot to resolve host». Как видите, всё достаточно логично и просто. Если у вас остались вопросы, спрашивайте в комментариях!
Это краткая статья покажет вам, как исправить ошибку ‘sudo: unable to resolve host’ в Ubuntu или любом другом дистрибутиве Linux.
Мы забыли дать ему разумное имя, поэтому через несколько дней мне пришлось изменить имя хоста и дать ему лучшее имя. Теперь он называется test-server, потому что для этого он и используется.
Мы создали пользователя sudo, потому что мы не рекомендуем все время быть пользователем root, особенно когда работаете со своей системой.
Когда мы начали использовать команды с sudo, то увидели странную ошибку в выводе команд:
Ошибка
sudo: unable to resolve host
Команда без проблем запускалась с sudo, но это сообщение об ошибке все равно отображалось.
Исправление sudo: unable to resolve host
Основная причина ошибки была связана с изменением имени хоста. Позвольте нам показать вам, как исправить эту проблему, чтобы устранить ошибку имени хоста.
Сначала проверьте имя хоста вашей системы с помощью команды hostname. В нашем случае имя хоста — тест-сервер.
$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: unable to resolve host’.
Чтобы исправить это, отредактируйте этот файл и добавьте новую строку и установите адрес обратной связи с именем хоста. Вы можете использовать редактор 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: unable to resolve host’ исчезла.
Мы надеемся, что этот быстрый маленький совет помог вам исправить эту раздражающую ошибку. Дайте нам знать, работает это у вас или нет в разделе комментариев.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
When I run sudo
the terminal is stuck for a few seconds and then outputs an error message. My terminal looks like this:
ubuntu@(none):~$ sudo true
sudo: unable to resolve host (none)
What can I do to solve it?
asked Aug 31, 2011 at 19:09
Kit SundeKit Sunde
10.9k7 gold badges25 silver badges32 bronze badges
7
Two things to check (assuming your machine is called my-machine
, you can change this as appropriate):
-
That the
/etc/hostname
file contains just the name of the machine. -
That
/etc/hosts
has an entry forlocalhost
. It should have something like:127.0.0.1 localhost.localdomain localhost 127.0.1.1 my-machine
If either of these files aren’t correct (since you can’t sudo), you may have to reboot the machine into recovery mode and make the modifications, then reboot to your usual environment.
answered Sep 1, 2011 at 3:26
Jeremy KerrJeremy Kerr
26.6k4 gold badges47 silver badges62 bronze badges
18
Edit /etc/hosts
and append your new hostname to the 127.0.0.1 line (or create a new line if you prefer that).
Mine looks like:
127.0.0.1 localhost localhost.localdomain penguin
# 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
Replace penguin
in the above example by your new hostname as stated in the /etc/hostname
file.
answered Apr 7, 2012 at 13:39
LekensteynLekensteyn
171k64 gold badges310 silver badges401 bronze badges
4
Add your hostname to /etc/hosts
like so:
echo $(hostname -I | cut -d -f1) $(hostname) | sudo tee -a /etc/hosts
answered Sep 15, 2014 at 16:03
Collin AndersonCollin Anderson
3,1261 gold badge16 silver badges12 bronze badges
4
Note, this is an answer to this question which has been merged with this one.
Your hostname (dave00-G31M-ES2L
) is not represented in /etc/hosts
. Add an L
to this line:
127.0.1.1 dave00-G31M-ES2
So it becomes:
127.0.1.1 dave00-G31M-ES2L
In order to accomplish this, open a console (press Ctrl+Alt+T) and type:
sudo gedit /etc/hosts
Add the letter L
as mentioned, save and exit.
answered Aug 18, 2012 at 11:02
ThorThor
3,45824 silver badges27 bronze badges
5
I had this issue when I was using ubuntu on a VPS. I solved it editing /etc/hosts file.
run this command:
sudo nano /etc/hosts
and then add:
127.0.0.1 localhost.localdomain localhost
127.0.1.1 ubuntu
I hope that will solve your issue
PS: Remember to reboot your computer!
answered Apr 1, 2013 at 1:18
Luca D’AmicoLuca D’Amico
5541 gold badge5 silver badges14 bronze badges
3
I was having the same issue even though the hostname in my /etc/hostname file and /etc/hosts file matched.
My hostname was «staging_1». It turns out that you can’t have an underscore in your hostname, which is why I was getting this error. Changing the underscore to a hyphen fixed my problem.
answered Aug 13, 2014 at 13:50
Chris.BChris.B
2412 silver badges4 bronze badges
0
In AWS, go to your vpc and turn on «DNS Hostnames».
answered Jan 15, 2015 at 5:15
ErickErick
1371 silver badge2 bronze badges
5
The symptom given in the question may correlate strongly with this more specific problem:
$ hostname --fqdn
hostname: Temporary failure in name resolution
There are different ways that this could be resolved, one of which is to add your hostname as localhost in /etc/hosts
(as shown in several other answers). This may be the right thing to do in general, but it isn’t the only possible resolution.
A «fully qualified domain name» may be supplied by an external DNS server or similar (if such is available on your network). In this case, sudo
will not complain, despite the missing entry in /etc/hosts
.
Note: sudo
attempts to dereference the hostname, even though it isn’t necessarily required, due to optional capabilities in the sudoers file. See sudo command trying to search for hostname.
As long as the delay isn’t too long, this error message is typically harmless.
answered Sep 18, 2017 at 22:17
Brent BradburnBrent Bradburn
2,7362 gold badges29 silver badges35 bronze badges
3
Everybody advises to modify /etc/hosts
. But in some cases this may not be possible (for example inside a docker container). So, I had to find a better way and I came up with this:
echo "alias sudo='sudo -h 127.0.0.1'" >> ~/.bash_aliases
source ~/.bashrc
Aliases don’t work in bash scripts, but we can use variables: sudo='sudo -h 127.0.0.1'
answered Jul 28, 2018 at 17:24
dashohoxhadashohoxha
3124 silver badges11 bronze badges
I encountered this same error message. I think this discussion thread at AWS Developer Forums is a better solution:
«Go the the VPC management console, select the VPC, click on Actions, select Edit DNS Hostnames and select Yes.»
https://forums.aws.amazon.com/thread.jspa?messageID=699718
answered Feb 13, 2016 at 11:44
user93581user93581
1171 silver badge2 bronze badges
Some terminal emulators will not update prompt with the correct hostname until you close and restart the emulator (lxterminal, I’m talking to you).
I spent 30min fighting with this error after editing my hostname and hosts files and running sudo service hostname restart
until I ran sudo hostname
and saw that the hostname was the new value, even though the prompt was showning the old value.
answered Jun 19, 2016 at 16:29
dagbeldagbel
611 silver badge1 bronze badge
1
In my case it was the problem, I changed the hostname
to man
because I wanted to know if there are some parameters you can use on hostname
. Instead it changed my hostname
to man
and I always got the same message like you
sudo: unable to resolve host (none)
after changing the hostname back to `localhost everything worked fine again
hostname localhost
answered Jan 9, 2014 at 22:24
XandruCeaXandruCea
1531 silver badge5 bronze badges
Sorry I can’t help you much but, since it says «can’t resolve host» try running:
hostname
And see if the output is the hostname of the machine. If not, the problem is the host configuration, not sudo.
answered Aug 31, 2011 at 19:16
animaletdesequiaanimaletdesequia
8,2964 gold badges26 silver badges43 bronze badges
3
OP wrote:
It was all in /etc/hostname. On two of our sick servers it looked like
this:ubuntu@(none):~$ cat /etc/hostname linux-web-n ip-10-128-##-##
While on a server without this issue we had:
ubuntu@ip-10-128-##-###:~$ cat /etc/hostname ip-10-128-##-###
Removed the
linux-web-n
portion, rebooted and everything was fine.
you might be getting an error if your hosts or hostname file contain illegal characters. Only these symbols are permitted: a-z, A-Z, 0-9
answered Jan 18, 2015 at 3:26
M.G.M.G.
1212 bronze badges
if you can’t sudo you CAN log in as root via su.
IE: su root (in an x-term).
then give the root password when prompted, then you can edit the files with nano. The root password in ‘buntu is the same as the password you would use for sudo.
answered Aug 24, 2016 at 15:07
1
I had this same problem! I changed my VPS’s name through the online admin control panel which did not change the machine name in the hosts file All I did was run:
sudo nano /etc/hosts
Then I edited it from this:
127.0.1.1 Megabyte Megabyte
127.0.0.1 localhost
To this:
127.0.1.1 Debian Debian
127.0.0.1 localhost
and that fixed my error! Hope this helped!
answered Jan 10, 2017 at 2:18
SynthSynth
211 bronze badge
In case your problem is that /etc/hostname
file and /etc/hosts
, both files have your desired hostname and still your machine is showing the error
sudo: unable to resolve host
Try, forcing the hostname
sudo hostname -F /etc/hostname
You will probably still get the same error, but try logging out and logging back in. It worked for me.
answered May 21, 2019 at 6:45
I had the same problem. I solved it by editing the /etc/hosts and /etc/hostname files… on the /etc/hosts file, just edit the top part as shown below.
#vi /etc/hosts
127.0.0.1 localhost
127.0.1.1 localhost myhostname
#vi /etc/hostname
myhostname
muru
191k52 gold badges468 silver badges719 bronze badges
answered Mar 26, 2016 at 17:53
CentyCenty
211 bronze badge
2
If you are using Vagrant, then login into the guest and run
apt-get --no-install-recommends install virtualbox-guest-utils
answered Jul 13, 2017 at 7:27
tanmoytanmoy
1011 silver badge4 bronze badges
Here’s a quick fix to get rid of the «unable to resolve host: Name or service not known» error on Linux.
After changing the hostname on your Linux system, you may encounter the error «unable to resolve host». Here’s what that means, and what you can do to fix it.
What Is a Hostname, and How Do You Change It?
When you set up your Linux system—whether it’s a VPS or a physical machine in your home—you may be asked to provide a hostname. This is a label your computer uses to identify itself to other machines on the network, to the user, and to itself.
Hostnames should be descriptive so that it’s easy to identify machines—even when you’re not sitting directly in front of them. «Kitchen PC», or «David’s tiny laptop» are great names. «racknerd-b7516a» is a terrible name and makes it difficult to work out exactly which machine you’re connected to.
One way of changing the hostname on Ubuntu or other Debian-based Linux distros is with the terminal.
Open a terminal by either pressing Ctrl + Alt + T, or by selecting it from your menu system, then enter:
sudo hostnamectl set-hostname your-new-hostname
Log out and then log back in, and you will see that the hostname has changed.
What Does «unable to resolve host: Name or service not known» Mean?
After changing your system’s hostname, the next time you try to run a command as sudo, you might receive a hostname error. In our case, the error was «unable to resolve host MUOVPS: Name or service not known».
This error does not prevent you from carrying out any tasks, but it can be annoying.
cat /etc/hostname
The aforementioned command will show the hostname you just set, but your new hostname is not present as an output of:
cat /etc/hosts
To fix this error, use nano to edit the file:
sudo nano /etc/hosts
On a new line, add the hostname of your machine—the hostname of our VPS is MUOVPS as shown below—then save and exit nano with Ctrl + O then Ctrl + X.
You Have Fixed the “unable to resolve host” Error!
Hostname errors are not the most serious and are unlikely to significantly disrupt your workflow or your day. But they are annoying and show that you haven’t configured your system properly. For this reason, it’s worth setting the hostname properly.
Fixing this issue requires you to edit the /etc/hosts file. Since it is a critical system file, knowing how to edit it properly is important to prevent any errors.
To totally unlock this section you need to Log-in
The error/warning defined in the subject of this article usually can be shown while using, for example, the apt-get tool on Ubuntu/Debian Linux distribution. This could happen after we have (finally) decided to change the hostname of our Linux system giving it a better name. Let’s say that wow it’s called test-server because that is we will use it for. Now, a common scenario would be that, after creating a sudo user because we do not prefer not to be root all the time, we start using commands with sudo, but at some point we see a strange error in the output of the commands:
unable to resolve host {your_hostname}: Name or service not known
The command run with sudo without any problem but this error message will be displayed anyway.
The Fix
The root cause of the error is actually related to the hostname changing. Let’s now show how to fix this unable to resolve hostname error. First, check the hostname of your system with hostname command. For example, let’s say that the hostname is test-server.
$hostname test-server
The hostname is taken from /etc/hostname file.
cat /etc/hostname test-server
The same hostname should be listed in the /etc/hosts file as well. But in our case (and basically in all the cases in which this error appears) the new hostname will miss in the /etc/hosts file as you can see in the output below:
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
Since it is missing from here, the system is not able to figure out the hostname and thus it throws the error sudo: unable to resolve host or unable to resolve host {your_hostname}: Name or service not known while using apt-get.
To fix this, edit this file and add a new line and set the loopback address with the new hostname (or just replace the old hostname with the new one). You can use Vim or Nano to edit files in command line.
127.0.0.1 <hostname>
So now, our /etc/hosts file looks like this:
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
Again, if the old hostname is still present anywhere in your /etc/hosts file, you should replace them with the new hostname (it is recommended).
Immediately after adding the above mentioned line, sudo: unable to resolve host or unable to resolve host {your_hostname}: Name or service not known errors will disappear.
Summary
Article Name
Unable to resolve host {hostname}: Name or service not known (Linux)
Description
The «Unable to resolve host» on Linux systems, while using sudo or apt-get on Terminal or on headless configurations could be annoying. The fix for this kind of scenario is simple and involves the system hostname.
Author
Publisher Name
Heelpbook.net
To test the tutorials on Linux Handbook, I created a new server on UpCloud, my favorite cloud server provider with blazing fast SSD. My Ubuntu 18.04 server was ready within minutes.
I forgot to give it a reasonable name so a few days later, I had to change the hostname and gave it a better name. Now it’s called test-server because that’s what it is used for.
I created a sudo user because I prefer not to be root all the time, specially when I am tinkering with my system.
When I started using commands with sudo, I saw a strange error in the output of the commands:
sudo: unable to resolve host test-server
The command ran with sudo without any problem but this error message was displayed anyway.
Fix sudo: unable to resolve host
The root cause of the error was actually related to the hostname changing. Let me show you how to fix this unable to resolve hostname error.
First, check the hostname of your system with hostname command. In my case, the hostname is test-server.
$hostname
test-server
The hostname is taken from /etc/hostname file.
cat /etc/hostname
test-server
The same hostname should be listed in the /etc/hosts file as well. But in my case (and I guess in your case as well) this hostname was missing from the /etc/hosts file as you can see in the output below:
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
Since it is missing from here, the system is not able to figure out the hostname and thus it throws the error ‘sudo: unable to resolve host’.
To fix this, edit this file and add a new line and set the loopback address with the hostname. You can use Vim to edit files in command line.
127.0.0.1 <hostname>
So now, my /etc/hosts file looks like this:
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
Tip: If the old hostname is still present anywhere in your /etc/hosts file, you should replace them with the new hostname.
Immediately after adding the above mentioned line, ‘sudo: unable to resolve host’ error disappeared. I didn’t even need to reboot my Ubuntu server.
I hope this quick little tip helped you to fix this irritating error. Let me know if it worked for you or not in the comment section.
Host or hostname is the specific name of the machine that is helpful over the network for identification purposes. Machines connect to the network and perform functionalities to send or receive packets through this name. Sometimes, an error “sudo: unable to resolve host” comes across while executing the command with root privileges.
This post will discover the possible reasons and the solutions to those reasons.
- Reason 1: Not Configure HostName
- Solution: Configure HostName
- Reason 2: Incorrect HostName
- Solution: Check the HostName of the System
Let’s start the article.
Reason 1: Hostname Not Configured
At the time of installing the Linux system, most users keep the default setting and do not assign any hostname, which is one of the reasons for the “sudo: unable to resolve host” error.
Solution: Configure HostName
To encounter the above error, modify the hostname in the “hosts” configuration file. You must access the host’s info file located at “/etc/hosts”.
The Nano Editor is utilized to access and modify the configuration file by specifying the file directory as given below:
The hostname and its IP address are highlighted in the above image (while the first entity is the localhost ).
Change Hostname
Modify the hostname by reaching through the arrow keys and changing the custom hostname. In our case, “myubuntu” is set here:
Restart the system
To apply these changes, type the “reboot” in the terminal to restart the system as below:
Verify the New Hostname
After restarting the system, you can verify that the hostname changes to “myubuntu” from the “ubuntu”:
Let’s see another reason with a solution.
Reason 2: Incorrect Hostname
One of the main reasons for the above error is changing the hostname and executing the “sudo” command in the terminal with the incorrect hostname.
Solution: Check the Hostname of the System
In network devices, the hostname is important to route traffic over the network. To check the hostname on Linux, various command line utilities are used. The hostname is one of them, as seen below.
After executing the above script, the machine’s hostname, “ubuntu”, is displayed here.
Conclusion
In the Linux system, the “sudo: unable to resolve host” error can be resolved by configuring the hostname properly. During configuration, users can modify the hostname through any editor and reboot the system to apply changes. Additionally, the hostname can be displayed by executing the “hostname” command in the terminal.