Hosts файл mac os. Как редактировать ​​файл Hosts на Mac и зачем это нужно делать? Рис. П9.1. Переход к папке

Hosts файл mac os. Как редактировать ​​файл Hosts на Mac и зачем это нужно делать? Рис. П9.1. Переход к папке

02.07.2020

Your Mac’s hosts file is a small, but important text document that has the ability to map hostnames to specified IP addresses. Although the modern Internet uses a variety of public and private DNS servers to map IP addresses, the hosts file is a handy way to override those DNS servers, allowing you to manually point a website address to the desired IP address, or block access to a site altogether by pointing to an unused or internal IP address.

Here’s how to edit the Mac hosts file on macOS (previously known as Mac OS X).

Edit Your Mac Hosts File with Text Edit

There are two primary ways to edit the hosts file in Mac OS X. The first is by using TextEdit since the hosts file is a plain text document. However, you can’t open the file directly, since it resides in a protected area of the file system. Instead, we need to copy the file to an unprotected location, like the Desktop, edit it, and then copy it back.

To find the hosts file, open the Finder, which you can access by clicking on the desktop, the smiley face finder in the lower left of your screen, or by pressing command + spacebar + “Finder” . Then follow these steps:



To open it, simply double-click and it will display the file’s contents in TextEdit (or the text editor of your choice).

Block IP Addresses

By default, the /etc/hosts file is relatively simple. It contains a number of lines of descriptive text which are “commented out” with the pound or number (also called a pound or hashtag) sign (#).

Any line that starts with a # sign is a comment and is not read by the /etc/hosts file. So comments are how you can add notes to your hosts file and comment out any lines that you want the /etc/hosts file to stop reading as entries but do not want to delete in case you need them in the future.

For each line, any text after the pound sign is ignored by the computer, making it a good way to add notes and descriptions to your files. It also contains default IP values for localhost and broadcasthost. To edit the file, you’ll add your own lines after broadcasthost.


In addition to testing newly developed websites and web hosting migrations, another reason to edit the hosts file is to block access to specific websites.

In our example, we’ll pretend that the computer we’re using is a device that we want to use exclusively for work, not allowing ourselves to get distracted by Facebook on our work machine.

To do this, type the IP address you wish to assign, followed by two tabs and the hostname. In our case, we want to block Facebook so we’ll map www.facebook.com to 0.0.0.0 which, as an invalid IP address, will result in an error.


Now, whenever we try to go to www.facebook.com from our Mac, the Web browser will fail to load the page, hopefully encouraging us to get back to work!

Reroute Web Addresses

Alternatively, you can enter the IP address of a valid site instead of 0.0.0.0, which will result in users attempting to access Facebook being directed to the site of your choosing.

To determine a website’s IP address, you can use the dig command, which comes standard with macOS. To “dig” the site via Terminal, we simply open up Terminal and then run the dig command on URL, which will then return the IP address as output.

$ dig www.сайт +short
104.25.27.105

Note: The +short option keeps the output to just the information we need, which is the IP address.

Make note of the IP address that’s returned and use it in your Mac hosts file mapping. For example, The New York Times website at www.nytimes.com returns an IP address of 170.149.172.130. If we map that to Facebook in our hosts file, any time someone using the Mac tries to go to Facebook, they’ll see The New York Times load instead.


Note: Many websites won’t allow you to map a domain name to the IP address currently mapped to the site so you’ll get a security error when you try.

You can add as many entries to the hosts file as you wish by entering new mappings on each line. Once you’ve made your desired changes to the hosts file, save it in its current location on the Desktop.

Then, drag and drop the hosts file from your Desktop back to its original location at /private/etc . If you’ve closed the Finder window pointing to this directory, simply use the Finder > Go > Go to Folder command, discussed above, to reopen it.

When you drop the hosts file back in its original location, macOS will ask you what to do about the unmodified hosts file that’s already there. Choose “Replace” and then enter your administrative user password to authenticate the transfer.

With the modified hosts file now in place, fire up your Web browser to test the changes.

Flush Your DNS Cache

In most cases, the new mapping should work immediately, but if you’re not seeing the correct behavior, you may need to flush your DNS cache, forcing the browser to read from your hosts file to determine the mapping.

To flush the DNS cache on your Mac, open Terminal and use the following command (sudo enables you to run this command as the admin of your machine):

$ sudo killall -HUP mDNSResponder

Note: You will need to enter your admin password to execute this command.

To get your Mac to clear your DNS cache, then confirm it’s cleared your cache by echoing a confirmation, enter these two commands separated by a semi-colon as shown here:

$ sudo killall -HUP mDNSResponder;say DNS cache has been flushed

Edit Your Mac Hosts File In Terminal With Nano

The steps in the previous section are easy enough, but if you want to avoid copying the hosts file you can edit it directly in Terminal using the UNIX Nano Text Editor, which is built into macOS.

To get started, launch Terminal, type the following command, and press Return. As with all sudo commands, you’ll need to also enter your admin password to execute it:
$ sudo nano /private/etc/hosts

You’ll now see the hosts file open in the Nano editor or vim or another editor of your choice. To navigate and edit the file in Nano, use the arrow keys on your keyboard.


Just as we did with the TextEdit method, above, we can add, edit, or remove hostname mappings at will. Because we launched Nano using sudo, any changes will be authenticated and saved directly to the original hosts file, without the need to copy it outside of its home directory.

When you’re done making changes, press Control-X to exit the editor, Y to save, and Return to overwrite the existing hosts file.

As we mentioned earlier, make sure to flush your DNS cache if you notice that your new mappings aren’t working properly.

Our examples mentioned blocking and redirecting distracting sites in a work environment but you can also use these steps to manually block access to malicious websites and, of course, other uses as well.

If you ever make a mistake and you’re not sure how to fix it, you can always restore the default hosts file contents by using one of the methods above to enter the following default information:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost::1 localhost
fe80::1%lo0 localhost

If you are a Mac user and found this article useful, you might want to check out other TechJunkie tutorials, including and

What’s the reason you are seeking to edit your Mac’s hosts file? How did it work out? Please tell us about it in the comments below!

Большинству из нас по тем или иным причинам приходилось сталкиваться с довольно важным в любой операционной системе файлом под названием "hosts" и его редактированием. Служит этот файл для сопоставления определенных доменных имен их сетевым адресам и, в отличие от DNS, контролируется администратором каждого конкретного компьютера, т.е. локально.

И если пользователи Windows, которые уже сталкивались с этим файлом и его редактированием знакомы с этим понятием и, скоре всего, помнят путь до нужного файла наизусть (но мы, на всякий случай, напомним -Windows\system32\drivers\etc\hosts), то новые пользователи компьютеров от Apple под управлением Mac OS X (macOS) поначалу часто теряются, не обнаружив искомый файл hosts по привычному для них пути, как, впрочем, и самого пути в их Маке.

Именно о том, где находится файл hosts на Mac и как его открыть и отредактировать мы и расскажем в этой подробной инструкции ниже.

К счастью, найти и отредактировать файл hosts на Mac ничуть не сложнее, чем сделать это в операционной системе от Microsoft. Нам известно как минимум два способа, о которых и пойдет речь ниже. Вы можете воспользоваться тем из них, которых вам покажется быстрее и удобнее.

Как открыть файл hosts через терминал Mac OS

Тем пользователям техники Apple, кто не боится слова "терминал", этот способ покажется наиболее быстрым и удобным. Для просмотра и редактирования файла hosts на Mac и введите в ней следующую команду.

sudo nano /private/etc/hosts

Также вам потребуется ввести пароль администратора, если он задан на компьютере.

Если вы всё ввели правильно, перед вами откроется содержимое файла hosts вашего Мака.

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

После внесения всех необходимых изменений нажмите сочетание клавиш "ctrl+X" для сохранения.

Нажмите клавишу "Y" для подтверждения сохранения изменений. Вот и всё, файл hosts успешно отредактирован.

Для того, чтобы сделанные изменения сразу же вступили в силу, иногда необходимо вашего Mac.

Как открыть файл hosts в текстовом редакторе

Для тех пользователей Mac"ов, которые ещё не очень хорошо "дружат" с Терминалом, есть альтернативный вариант открыть и изменить файл hosts при помощи любимого текстового редактора и стандартного файлового менеджера Finder.

Для этого кликните правой кнопкой мыши (или используйте аналогичное действие трекпада) по иконке Finder на нижней панели (Dock) вашего компьютера и выберите в выпадающем меню пункт "Переход к папке..." .

В открывшемся окне введите путь, по которому находится файл hosts в компьютерах с операционной системой OS X и нажмите кнопку "Перейти". Выглядит путь следующим образом.

В результате откроется окно Finder"а в папке, в которой искомый файл и расположен. Он будет уже выделен. Просто кликните по нему правой кнопкой и откройте его с помощью вашего любимого текстового редактора (подойдет и стандартный TextEdit).

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

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

Это всё. В результате описанных действий ваш компьютер будет использовать уже новый файл hosts. Но иногда, для того, чтобы изменения вступили в силу сразу же, вам может понадобиться обновить кэш DNS. Об этом ниже.

Обновите кэш DNS

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

dscacheutil -flushcache; sudo killall -HUP mDNSResponder

После этого указанные в новом файле hosts правила точно будут работать так, как надо.

Если вы настраиваете новый веб-сервер или другое устройство, которое подключается к Интернету, и хотите протестировать его, прежде чем оно появится в сети, либо прежде чем у вас возникнут проблемы со шпионскими и рекламными сетями, то на компьютере есть невидимый файл, который может помочь. Этот файл называется Hosts , а ниже описано, как его использовать.

Система доменных имен

Когда вы вводите доменное имя любого сайта, хотите увидеть все, что происходит «за кулисами». Каждый сайт, каждый сервис и практически каждое устройство, подключенное к Интернету, обладает уникальным числовым адресом, который говорит о местонахождении других устройств – это TCP/IP адрес. Система доменных имен (DNS) преобразует эти числовые адреса в нечто более узнаваемое и запоминающееся для человека (к примеру, «www.microsoft.com»).

Когда вы впервые вводите адрес сайта, ваш Mac пингует сервер DNS. Ваш Mac накапливает скрытый кэш-файл, чтобы помнить эти детали позже, когда вы посетите тот же сайт снова.

Файл Hosts

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

Есть некоторые практические причины, почему вам нужно использовать файл Hosts , а не просто позволять DNS делать свою работу. К примеру, вы тестируете сервер разработки, который собираетесь привести в действие, и хотели бы использовать собственное доменное имя вместо конкретного IP-адреса устройства. Перед онлайн системами и доступом к любому использующемуся DNS, вы можете использовать файл Hosts вместо «Введите IP-адрес устройства». Когда вы используете доменное имя, Mac автоматически перейдет на данное устройство.

Также вы можете использовать файл Hosts , чтобы заблокировать или обойти шпионские и рекламные сети посредством "обнуления" их IP-адресов – введя 0.0.0.0, а затем имя домена, который хотите заблокировать.

Как отредактировать файл Hosts

Лучше всего работать с файлом Hosts через специальное приложение Terminal, которое расположено в папке «Утилиты» на компьютере. Вам нужно узнать IP-адрес устройства, на которое нужно перенаправить на ваш компьютер Mac, либо доменные имена, которые вы пытаетесь сохранить отдаленно от своего компьютера.

· Дважды щелкните на Terminal.

· Введите sudo nano /etc/hosts и нажмите Return.

· Вам будет предложено ввести пароль. Введите пароль администратора.

Теперь вы в текстовом редакторе Nano. Если хотите добавить новое устройство или домен, переместите курсор с помощью клавиш управления курсором и зафиксируйте его после текста, который вы видите, затем начинайте вводить. Если вы сопоставляете особый IP адрес в вашей локальной сети к домену, то можно ввести IP-адрес, нажать Tab, а затем ввести имя домена.

И наоборот, если хотите убедиться, что URL-адрес не переходит на сайт, используйте «127.0.0.1». Это сопоставит его обратно в ваш компьютер. Даже если вашему компьютеру присваивается разный IP-адрес его маршрутизатором, 127.0.0.1 будет по умолчанию использоваться на локальном компьютере благодаря стандартным настройкам в файле Hosts .

Как только вы закончите, нажмите и удерживайте control и клавишу O, чтобы сохранить файл, а затем – control и X для выхода. Вернитесь к командной строке и введите «sudo killall -HUP mDNSResponder», а затем – return. Это очистит DNS кэш вашего компьютера и не собьется изменениями, которые вы сделали в файле Hosts .

Не забывайте, что вы изменили файл Hosts , так как в любой момент может понадобиться отменить изменения, которые вы сделали, чтобы сохранить правильную работу компьютера.

Как редактировать ​​файл Hosts на Mac и зачем это нужно делать?:
рейтинг 80 из 80 на основе 80 оценок.
Всего 80 отзывов.

Need to edit or modify the hosts file on a Mac? This guide will show you exactly how to edit the hosts file in Mac OS. You’ll find hosts in Mac OS X is stored at /private/etc/hosts but it can also be accessed at the more traditional location of /etc/hosts. That said, if you’re looking to edit hosts, you’ll want to target the file located in /private/etc/ though.

We’ll walk through how to manually edit the hosts file in MacOS Mojave, MacOS Catalina, MacOS High Sierra, MacOS Sierra, OS X El Capitan, Yosemite, OS X Lion, OS X Mountain Lion, and OS X Mavericks, this will be done with the command line using the simple text editor called nano. Don’t let the command line or Terminal sound intimidating though because it’s not, we’ll make the entire process of editing a Mac hosts file super easy.

How to Edit Hosts File on Mac OS

Let’s get started making some edits to /etc/hosts in macOS and Mac OS X!

  1. Launch Terminal, found in /Applications/Utilities/ or launched through Spotlight
  2. Type the following command at the prompt:
  3. sudo nano /private/etc/hosts

  4. Enter the administrator password when requested, you will not see it typed on screen as usual with the command line
  5. Once the hosts file is loaded within nano, use the arrow keys to navigate to the bottom of the hosts file to make your modifications
  6. When finished, hit Control+O followed by ENTER/RETURN to save changes to /private/etc/hosts, then hit Control+X to exit out of nano
  7. Quit out of Terminal when finished

You can verify your hosts modifications immediately with ping, Safari, or any other network app.

Changes take effect immediately though some adjustments may need to be accompanied by a which can be done with the following command in macOS 10.12+ through OS X 10.9:

dscacheutil -flushcache;sudo killall -HUP mDNSResponder

When flushing DNS cache with that command you will need to enter the admin password.

If you’d like to see how this entire process is accomplished before doing it yourself, watch the video below to see a demonstration of the hosts file being modified on OS X to block the website ‘yahoo.com’ from loading:

Note: the procedure is the same with older versions of Mac OS X, though the path to hosts could be /etc/hosts if the version of OS X is dated significantly.

Tips to Consider When Editing Hosts Files

The following tips go beyond OS X and apply to any hosts file, be it on a Mac, Windows, or Linux.

  • The preceding IP address is where the following domain will resolve to
  • Always add new hosts to their own unique line
  • The # symbol functions as a comment, it can be used to add comments to hosts entries or to comment out hosts modifications
  • You by adding them to the file and sending them nowhere, preventing access
  • You can redirect websites locally using the same logic, perfect for
  • With some modifications, it can be necessary to with dscacheutil before the changes take effect
  • For juggling multiple hosts files consider using a
  • If the hosts file claims to be locked, it’s because you did not prefix the edit with the “sudo” command
  • Consider making a backup of hosts if you plan on making significant modifications, or it’s your first time editing the file (process described below)

Making a backup of the hosts file can be a good idea if you plan on making significant changes or just want to play around with modifications and see what happens, a simple way to do that would be to use this command, which would store a backup in your home ~/Documents/ folder:

sudo cp /private/etc/hosts ~/Documents/hosts-backup

Then, if you wanted to restore the modified hosts to the backup of the original file, you just have to swap the paths like so and rename the file again:

sudo cp ~/Documents/hosts-backup /private/etc/hosts

That’s it, though again you may need to flush the DNS for changes to take effect.

Finally, it’s worth mentioning that if you’d prefer to avoid the Terminal and the command line completely, you could to modify the contents of hosts that way through System Preferences instead. Generally speaking though, we recommend just using the tools that are built directly into the Mac.

Let us know in the comments if you have any questions or tips.

В операционной системе Mac OS файл hosts находится в папке /etc. Его можно отредактировать с помощью визуального текстового редактора.

Прежде всего, вам необходимо предоставить себе доступ к изменению папки /etc и к расположенному в ней файлу hosts. Для этого откройте в окне Finder вкладку Переход , и щелкните строку (рис. П9.1).

Рис. П9.1. Переход к папке.

На экране появится окно . Вам нужно ввести в одноименном поле строку /etc, как это показано на рис. П9.2, а затем щелкнуть кнопку Перейти .


Рис. П9.2. Ввод имени папки.

Вы увидите довольно большой список файлов, расположенных в папке /etc (рис П9.3).


Рис. П9.3. Файлы в папке /etc.

После того как вы перешли к папке /etc, необходимо настроить права доступа. По умолчанию у вас нет прав для изменения файла hosts, их придется добавить вручную.

Чтобы добавить права доступа, сразу после перехода к папке выберите изменю Файл строку Свойства . Вы увидите окно настройки свойств папки etc, показанное на рис. П9.4.


Рис. П9.4. Добавление прав доступа.

Здесь вам нужно сначала разблокировать изменения, щелкнув изображение замка в левом нижнем углу окна, а затем при помощи значка "+" добавить свою учетную запись и разрешить для нее операции Чтение и запись. На рис. П9.4 эти права уже добавлены.

На следующем этапа добавьте такие же права на файл hosts. Для этого найдите файл в списке, показанном на рис. П9.3, выделите файл, а затем снова выберите изменю Файл строку Свойства . Теперь вы увидите окно настройки свойств файла hosts, аналогичное показанному на рис. П9.4. Добавьте в этом окне свою учетную запись и права, по аналогии с папкой /etc.

После изменения прав щелкните файл hosts дважды для редактирования. Появится окно редактора, показанное на рис. П9.5.


Рис. П9.5. Редактирование файла hosts.

Вам нужно будет дописать в конец файла строки, полученные от нашей технической поддержки, а затем сохранить файл.



© 2024 beasthackerz.ru - Браузеры. Аудио. Жесткий диск. Программы. Локальная сеть. Windows