файл hosts проигнорировал, как диагностировать?

Чистый корень является идентификатором пользователя "0".

Все пользователи в системе находятся в/etc/passwd файле:

less /etc/passwd

Те, кто корень, имеют "0" как идентификатор пользователя, который является 3-м столбцом. У тех, которые имеют "0" как группа (4-й столбец) могут также быть некоторые полномочия пользователя root.

Затем, Вы захотите посмотреть на группы и видеть, кто дополнительный член групп "колеса" или "корня" или "администратора":

less /etc/group

У пользователей, перечисленных в тех группах, могли быть некоторые полномочия пользователя root, особенно через команду "sudo".

Заключительной вещью, которую Вы захотите проверить, является конфигурация "sudo", и посмотрите, кто перечислен как наличие авторизации выполнить эту команду. Этот файл сам хорошо документируется так, я не воспроизведу его здесь:

less /etc/sudoers

Это покрывает основные области того, у кого мог быть корневой доступ.

151
задан 13 April 2017 в 15:14
11 ответов

Based on my own experience and what I encountered while Googling, here are some things to try:

1. Did you check that it works correctly?

Changes to hosts should take effect immediately, but Windows caches name resolution data so for some time the old records may be used. Open a command line (Windows+R, cmd, Enter) and type:

ipconfig /flushdns

To drop the old data. To check if it works, use (assuming you have an ipv4 entry in your hosts for www.example.com, or an ipv6 entry in your hosts for ipv6.example.com):

ping www.example.com -n 1
ping -6 ipv6.example.com -n 1

And see if it uses the correct IP. If yes, your hosts file is fine and the problem is elsewhere.

Also, you can reset the NetBios cache with (open the console as an admin or it will fail):

nbtstat -R

You can check the current data in the DNS cache with:

ipconfig /displaydns | more

2. Basics

  • Is your hosts file named correctly? It should be hosts and not host, etc.
  • Is the extension correct? It should have no extension (hosts not hosts.txt) - be careful if you have configured windows to hide known extensions, check the properties to be sure: The correct hosts file's type will show up as just "File".
  • Did you follow the correct syntax? Did you accidentally prefix lines with a hash (#) which indicates comments?
  • Did you take care of all variants (www.example.com and example.com - safest to just add both)?

3. Whitespace

The format for each line is IP address, then a horizontal tab (escape code \t, ASCII HT, hex 0x09) or a single space (hex 0x20), then the host name, ie. www.example.com, then finally a carriage return followed by a line feed, (escape codes \r\n, ASCII CRLF, hex 0x0d 0x0a).

Sample entries, using Unicode control pictures to indicate control characters. (Don't copy and paste these into your hosts file!)

192.0.2.1␉www.example.com␍␊
2001:db8:8:4::2␉ipv6.example.com␍␊

The individual bytes may be viewed in Notepad++ with the hex editor plugin. Notepad++ will also show special characters (View -> Show Symbol) so you can easily inspect the number and kind of whitespace characters.

If you copied and pasted hosts entries from somewhere, you may end up with multiple spaces. In theory hosts supports multiple spaces separating the two columns, but it's another thing to try if nothing else works.

To be on the safe side, make sure all lines in your hosts file either use tabs or spaces, not both.

Lastly, terminate the file with a blank line.

4. Registry Key

There is a registry key specifying the location of the hosts file. Supposedly, Windows doesn't actually support putting the hosts file in other locations, but you might want to check. The key is:

\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DataBasePath

The entry should be:

%SystemRoot%\System32\drivers\etc

5. Permissions

Sometimes there are issues with permissions on the file, the file attributes, and similar things. To recreate the file with default permissions:

  1. Create a new text file on your desktop.
  2. Copy and paste the contents of your current hosts file into this file in Notepad.
  3. Save the new text file and rename it to hosts.
  4. Copy (do not move) the file to your %SystemRoot%\System32\drivers\etc directory, and overwrite the old file.

Last point is important: Copying works, moving doesn't.

The local Users account must be able to read the hosts file. To make sure (in Windows 7):

  1. Navigate to %SystemRoot%\System32\drivers\etc in Windows Explorer.
  2. If you can't see the hosts file, ensure you can see hidden and system files.
  3. Right-click on the hosts file and select Properties from the context menu.
  4. In the hosts Properties window, click on the Security tab.
  5. Examine the list of names in the Group or user names: box. If %COMPUTERNAME%\Users is present, click on it to view permissions.
  6. If Users is not present, or is present but does not have Read permission, click Edit....
  7. If Users is not present, click Add..., type Users, click Check Names, and click OK or press Enter.
  8. Select Users, and ensure Read & execute is checked in the Allow column. Click OK. If a Windows Security alert box pops up, choose Yes to continue.
  9. Click OK to close the hosts Properties window.
  10. Go up to section 1 of this answer and follow the directions to check if it's working now.

6. Encoding

The hosts file should encoded in ANSI or UTF-8 without BOM. You can do this with File -> Save As.

7. Proxies

If you have a proxy configured, it may bypass the hosts file. The solution is to not use the proxy, or configure it to not do this.

To check, go to your Internet Explorer -> Internet Options -> Connections -> LAN settings. If everything is blank and "Automatically detect settings" is checked, you aren't using a proxy.

If you rely on a proxy to access the web and therefore don't want to disable it, you can add exceptions by going to Internet Explorer -> Internet Options -> Connections -> LAN settings -> Proxy Server / Advanced. Then add your exceptions to the Exceptions text box. E.g. localhost;127.0.0.1;*.dev

8. DNS address

(This may also resolve proxy issues.)

Go to your network connections properties, then TCP/IP settings, and change the first DNS server to 127.0.0.1 (localhost). The second should probably be your actual DNS's IP.

This is not necessary for the hosts file to work, but it may help in your case if something is configured strangely.

9. .local addresses

If you are using a .local domain entry in the form of myhost.local and it gets ignored please try the following

x.x.x.x myhost.local www.myhost.local

even if the www.myhost.local does not exist. Windows somehow does not append its workgroup or localdomain.

221
ответ дан 28 November 2019 в 19:17

Убедитесь, что вы указали ipaddress первым и затем «домен» выглядит следующим образом:

127.0.0.1   bo.dev
127.0.0.1   www.bo.dev
16
ответ дан 28 November 2019 в 19:17

В моих случаях я пробовал создать файл Windows 7: C: \ Windows \ System32 \ drivers \ etc \ hosts.ics.

hosts.ics:

# This file has been automatically generated for use by Microsoft Internet
# Connection Sharing. It contains the mappings of IP addresses to host names
# for the home network. Please do not make changes to the HOSTS.ICS file.
# Any changes may result in a loss of connectivity between machines on the
# local network.

В качестве в результате Windows игнорирует настройки в C: \ Windows \ System32 \ drivers \ etc \ hosts и использует их из hosts.ics.

7
ответ дан 28 November 2019 в 19:17

Я потратил на это часы, возможно, дни.

Безопасность IBM Trusteer Endpoint Rapport может вызвать эту проблему.

Я добавил mysite.com в его список доверенных сайтов.

Я думаю, что в рамках своей безопасности он предотвращает попадание вредоносных программ или вирусов на альтернативные сайты.

Взял свой сайт из списка доверенных сайтов, и он больше не проверяет и «исправляет» перенаправление файлов моих хостов.

Надеюсь, что это поможет кому-нибудь решить их проблему.

1
ответ дан 28 November 2019 в 19:17

Пожалуйста, добавьте проверку файловых разрешений. Я обнаружил, что несмотря на то, что у меня есть права локального администратора на компьютер и, следовательно, на хосты. Этого не произошло до тех пор, пока я не добавил локальных пользователей к файловым правам хостов с помощью Read and Read & Execute, а затем ipconfig /flushdns. Что хосты стали активными.

11
ответ дан 28 November 2019 в 19:17

Одна проблема, упущенная в обсуждении выше, - это неквалифицированные имена (имена без точки) в файле hosts. В этот момент могут сработать настройки вашей сети и автоматически добавить ваш собственный домен в конец неквалифицированного домена. Следовательно, имя может не разрешиться или, что еще хуже, преобразоваться в совершенно другую машину.

1
ответ дан 28 November 2019 в 19:17

В окнах убедитесь, что HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DataBasePath указана директория файла hosts

.
0
ответ дан 28 November 2019 в 19:17

В моем случае проблема была в том, что я копировал файл hosts из зашифрованного каталога и переопределял им и т.д./хозяев. Я должен был посмотреть на свойства и убрать флажок "encrypt file".

.
0
ответ дан 28 November 2019 в 19:17

У меня возникла та же проблема: записи файлов хостов игнорировались. Я пробовал все в этой и многих других темах, но безуспешно. Я подумал, что опубликую то, что сработало для меня, на случай, если кто-то еще столкнется с этим.

  1. Откройте проводник Windows от имени администратора
  2. УДАЛИТЬ файл hosts
  3. Откройте блокнот от имени администратора и создайте новый файл hosts
  4. Начните с нуля и добавьте записи.
  5. Убедитесь, что файл hosts не имеет .txt extension

Примечание: простое открытие файла hosts и удаление содержимого, проверка того, что он равен 0 КБ, и повторное добавление не помогли. Я подозреваю, что у файла возникла проблема с разрешениями.

3
ответ дан 28 November 2019 в 19:17

Убедитесь, что вы ввели значения как IP NAME , а не как NAME IP .

Это может произойти, если есть, скажем , только одна запись в файле, и когда вы игнорируете текст комментария.

1
ответ дан 28 November 2019 в 19:17

Мой файл hosts игнорируется до тех пор, пока у меня не будет сетевое соединение на моем ноутбуке (Windows 7). Как только я подключаюсь к сети, все работает должным образом. Очевидно, что без сети я не могу пинговать хосты и т. Д., Но я все еще ожидал, что Windows получит свои IP-адреса из файла hosts. Это не так. Даже после отключения он все еще ищет адреса в порядке, но между перезагрузкой компьютера и первым подключением к сети он игнорирует файл hosts.

(Между прочим, табуляции, пробелы и отсутствие возврата каретки не имеют значения, насколько я могу судить ).

0
ответ дан 28 November 2019 в 19:17

Теги

Похожие вопросы