Ошибка sudo unable to resolve host

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 Sunde's user avatar

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):

  1. That the /etc/hostname file contains just the name of the machine.

  2. That /etc/hosts has an entry for localhost. 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.

Thomas Ward -On Strike's user avatar

answered Sep 1, 2011 at 3:26

Jeremy Kerr's user avatar

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.

Community's user avatar

answered Apr 7, 2012 at 13:39

Lekensteyn's user avatar

LekensteynLekensteyn

171k65 gold badges311 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 Anderson's user avatar

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.

Community's user avatar

answered Aug 18, 2012 at 11:02

Thor's user avatar

ThorThor

3,46825 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'Amico's user avatar

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.B's user avatar

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

Erick's user avatar

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 Bradburn's user avatar

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

dashohoxha's user avatar

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

user93581's user avatar

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

dagbel's user avatar

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

XandruCea's user avatar

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

animaletdesequia's user avatar

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.'s user avatar

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

ken scharf's user avatar

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

Synth's user avatar

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

GypsyCosmonaut's user avatar

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's user avatar

muru

192k52 gold badges468 silver badges719 bronze badges

answered Mar 26, 2016 at 17:53

Centy's user avatar

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

tanmoy's user avatar

tanmoytanmoy

1011 silver badge4 bronze badges

Некоторые пользователи сталкиваются с ошибкой «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 License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

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 Sunde's user avatar

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):

  1. That the /etc/hostname file contains just the name of the machine.

  2. That /etc/hosts has an entry for localhost. 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.

Thomas Ward -On Strike's user avatar

answered Sep 1, 2011 at 3:26

Jeremy Kerr's user avatar

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.

Community's user avatar

answered Apr 7, 2012 at 13:39

Lekensteyn's user avatar

LekensteynLekensteyn

171k65 gold badges311 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 Anderson's user avatar

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.

Community's user avatar

answered Aug 18, 2012 at 11:02

Thor's user avatar

ThorThor

3,46825 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'Amico's user avatar

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.B's user avatar

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

Erick's user avatar

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 Bradburn's user avatar

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

dashohoxha's user avatar

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

user93581's user avatar

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

dagbel's user avatar

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

XandruCea's user avatar

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

animaletdesequia's user avatar

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.'s user avatar

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

ken scharf's user avatar

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

Synth's user avatar

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

GypsyCosmonaut's user avatar

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's user avatar

muru

192k52 gold badges468 silver badges719 bronze badges

answered Mar 26, 2016 at 17:53

Centy's user avatar

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

tanmoy's user avatar

tanmoytanmoy

1011 silver badge4 bronze badges

Некоторые пользователи сталкиваются с ошибкой «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

Это краткая статья покажет вам, как исправить ошибку  ‘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.

  • Ошибка su 41766 4 ps4
  • Ошибка sud на стиральной машине samsung при отжиме
  • Ошибка su 41350 3 на консоли ps4
  • Ошибка sud 5 стиральная машина лджи
  • Ошибка su 41350 3 ps4 решение