- Где находится файл hosts в Mac OS X и как его отредактировать
- Как открыть файл hosts через терминал Mac OS
- Как открыть файл hosts в текстовом редакторе
- Обновите кэш DNS
- Как отредактировать файл Hosts на Mac
- How to Edit the Hosts File on macOS (Mac OS X)
- How to Edit Your Mac Hosts File with Text Edit
- Block IP Addresses
- Reroute Web Addresses
- Flush Your DNS Cache
- How to Edit Your Mac Hosts File In Terminal With Nano
- Final Thoughts
Где находится файл hosts в Mac OS X и как его отредактировать
Большинству из нас по тем или иным причинам приходилось сталкиваться с довольно важным в любой операционной системе файлом под названием «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 откройте программу «Терминал» и введите в ней следующую команду.
Также вам потребуется ввести пароль администратора, если он задан на компьютере.
Если вы всё ввели правильно, перед вами откроется содержимое файла hosts вашего Мака.
Внесите необходимые изменения в этот файл (курсор мыши в терминале не работает, для перемещения между строками используйте стрелочки клавиатуры), к примеру, добавьте сайт, который вы хотите заблокировать.
После внесения всех необходимых изменений нажмите сочетание клавиш «ctrl+X» для сохранения.
Нажмите клавишу «Y» для подтверждения сохранения изменений. Вот и всё, файл hosts успешно отредактирован.
Для того, чтобы сделанные изменения сразу же вступили в силу, иногда необходимо сбросить кэш DNS вашего 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 на Mac
Компьютерные пользователи всегда имели две градации: любители и продвинутые пользователи. Так вот для первых объяснять значение и сущность файла hosts, способов его редактирования, видимо не имеет смысла, а значит материал данной статьи предназначен исключительно для пользователей, которые постоянно интересуются, как же работают их домашние или офисные помощники.
Всем остальным советуем не терять времени, а заняться более интересными и полезными делами.
Иногда, редактирование файла hosts необходимо после использования утилиты TinyUmbrella, которая служит для перенаправления Вашего iOS устройства с IP адреса серверов Apple к серверам Саурика (Saurik), т.е. Cydia. Этот обман необходим для того, чтобы воспользоваться сохраненными цифровыми подписями SHSH, и тем самым получить возможность для установки кастомных прошивок прошлых версий iOS (откат, понижение, downgrade).
Так вот, после запуска, TinyUmbrella может вносить в файле hosts «нужные строчки», однако, если потом потребуется восстановление iOS устройства на официальную прошивку, то iTunes обязательно выдаст Вам ошибку, которая и будет означать, что программа, а вместе с ней Ваше устройство не может связаться с серверами Apple. Как правило лечением будет удаление строки 74.208.105.171 gs.apple.com из файла hosts.
Итак, существует два способа редактирования файла hosts на Mac. Один из них с использованием родного приложения Терминал:
- запускаем программу Терминал. Она находится в папке Приложения -> Утилиты (еще можно применить комбинацию клавиш Shift+Cmd+U при активном окне Finder);
- открываем hosts (через команду sudo nano /etc/hosts);
- вводим пароль, допускающий к установке новых программ;
- редактируем файл.
Редактирование осуществляется следующими комбинациями клавиш:
- следующая/предыдущая страница – Ctrl+V/ Ctrl+Y;
- создать запись – после набранного текста, курсор переводим в конец и жмем Ctrl+O;
- выйти из файла — Ctrl+Х;
- удалить запись – перевести курсор к удаляемой строке и нажать Ctrl+К;
- отмена удаления — Ctrl+U.
Существует еще один способ редактирования файла hosts. При этом используется Finder и простой текстовый редактор.
В окне Finder находим вкладку Переход -> Переход к папке (либо Shift+Cmd+G);
- в запустившимся окошке вбиваем строчку /etc и жмем «Перейти»;
- находим файл с именем hosts и двойным кликом открываем его;
- запустится обычный текстовый редактор с информацией из файла hosts, единственный минус, все изменения невозможно будет сохранить из-за ограничений доступа.
Если имеется необходимость в немедленном вступлении в силу произведенных изменений, специалисты рекомендуют обновить DNS записи с помощью «Терминал» (команда dscacheutil –flushcache).
Источник
How to Edit the Hosts File on macOS (Mac OS X)
Your Mac’s hosts file is a small but important text document that has the ability to map hostnames to specified IP addresses.
While 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.
Let’s take a quick look at how to edit the Mac hosts file on macOS.
How to 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 cmd + Spacebar + Finder.
- Now, select the Go drop-down menu.
3. Then, select Go to Folder from the menu.
4. In the box, enter “/private/etc/hosts” into the box and press Return.
5. A new Finder window will open and your Mac’s hosts file will be selected. Click and drag it out of the Finder window and drop it on your desktop.
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. 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.
- Now, type “ $ dig www.techjunkie.com + short 104.25.27.105 “
Note: The + short option keeps the output to just the information we need, which is the IP address.
3. 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 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.
4. 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.
5. 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.
6. 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):
- Now, type “ sudo killall -HUP mDNSResponder ” and press Return. 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 “
Your Mac will then come through the speakers saying “DNS cache has been flushed.”
How to 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 “
2. 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.
3. 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.
4. 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
Final Thoughts
Knowing how to edit the hosts file on macOS offers a convenient way to override DNS servers and manually point a website address to a new IP address or block access, and by following the steps outlined above, you can accomplish this task very quickly.
If you are a Mac user and found this article useful, you might want to check out other TechJunkie tutorials, including How to Find Your Mac’s Exact CPU Model and How To Flush the DNS in Mac Mojave.
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!
Источник