Host file windows sample

Что такое файл hosts. Как ограничить доступ к сайтам стандартными способами windows

Для чего нужен файл Hosts?
Предназначение этого системного файла — присвоение определенным адресам сайтов определенного IP.
Этот файл очень любят всякого рода вирусы и зловреды для того, чтобы прописать в него свои данные или попросту его заменить.
Результатом этих действий могут быть признаки «вставки» сайта в браузеры, который будет просить отправить смс при открытии браузера или блокировка различных сайтов, на усмотрение создателей вируса.

Где находится файл hosts в windows?
Для различных версий ОС Windows расположение файла hosts немного разное:

Причем окончание hosts, это уже и есть конечный файл, а не папка. У него нет расширения.

Как должен выглядеть правильный файл hosts?
«Содержимое» файла hosts так же немного отличается для разных версий windows, но не особо. В нем «написано» на английском языке для чего он нужен и как делать исключения с приведением одного примера. Все строчки, начинающиеся со знака # , означают что они закомментированы и не влияют на файл.
Содержание оригинального файла hosts для Windows XP:

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a ‘#’ symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host

# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost

Как Вы можете убедиться, в содержании файла host для разных версий windows, особых отличий нет.

Как открыть и изменить файл hosts?
Файл hosts можно открыть с помощью стандартного Блокнота Windows.
Вот здесь, наверное, самая интересная часть статьи.
Прежде всего нужно понять, а зачем вообще изменять этот файл? Да для того, чтобы запретить доступ к определенным сайтам. Таким образом, изменив данный файл и прописав в него адрес сайта, пользователь не сможет зайти на него ни через какой браузер.
Для того, чтобы изменить файл hosts, желательно открыть его от имени администратора (Как запустить файл или программу от имени администратора) щелкнув ПКМ на файле и выбрав «Запуск от имени администратора». Либо открыть таким образом Блокнот и уже в нём открыть файл.

Для быстроты действий можно просто нажать кнопку Пуск и выбрать пункт Выполнить (win+r) (Что делать, если в Пуск нет Выполнить) и ввести в строку:

В результате чего откроется этот файл в Блокноте.

Для того, чтобы заблокировать доступ к сайту (предположим, он будет test.ru ), нужно просто добавить строку с этим сайтом в самый низ:

# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a ‘#’ symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host

Читайте также:  Установка arch linux 2021 bios

# This HOSTS file created by Dr.Web Anti-rootkit API

# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 test.ru

Каждый новый сайт, который хотите заблокировать, нужно начинать с новой строки и прописывать, не забывая локальный IP адрес 127.0.0.1

Так же, для редактирования файла hosts, существует программа HOSTS EDITOR, скачать которую и почитать описание можно с официального сайта .
Принцип работы у неё заключается в том, что она помогает отредактировать файл hosts.
Из скрина ниже понятен принцип её работы, всё делается в пару кликов. Добавление осуществляется путем нажатия на + .

После редактирования не забудьте нажать на кнопку сохранения (2 кнопка «Save changes» слева от кнопки «+»).

Так же изменить этот файл можно и для хороших целей, например ускорить загрузку сайта.
Как это работает?
При заходе на сайт, Вы видите его доменное имя, которое имеет буквы. Но все сайты в интернете имеют IP адрес, а названия уже присваиваются с использованием DNS. Я не буду вдаваться в подробности этого процесса, статья не об этом. Но здесь нужно знать то, что файл hosts имеет приоритет при обращении к сайтам, и только после него идет запрос к DNS.
Для того, чтобы ускорить загрузку сайта, нужно знать его IP адрес и домен.
IP адрес сайта можно узнать с помощью различных сервисов, например этого или этого .
Домен — это название сайта.
Для примера, ускорим загрузку этого сайта, на котором Вы читаете статью, явно указав файлу IP адрес и домен.
Тогда добавляемая строчка будет:

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

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

И теперь, после ввода в адресную строку браузера сайта test.ru , Вы будете перенаправлены на сайт, указанный в IP адресе. В данном случае на сайт vindavoz.ru .

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

Некоторые нюансы в файле hosts:

  • Всегда проверяйте, есть ли у Вас сбоку полоса прокрутки и всегда прокручивайте окно донизу. это связанно с тем, что некоторые вирусы прописываются в область, скрытую за пределы окна.
  • В некоторых случаях, обычно если не получается сохранить файл, нужно войти под учетной записью Администратора.
  • Иногда, из-за вирусов, этот файл может быть скрытым. Читайте статью Скрытые файлы и папки.
  • В двух описанных способах (перенаправление и ускорение) может не получится желаемый результат. Дело в том, что на одном IP адресе может находится несколько сайтов, особенно это актуально для внешних IP адресов, которые дают сервисы.
  • В связи с тем, что вирусы любят этот файл, его атрибуты можно изменить на Скрытый и Доступный только для чтения.
  • Проверьте атрибуты файла, если не удается сохранить файл hosts.
    Читайте также:  Шумоподавление для usb микрофона windows 10

    Таким образом Вы можете легко и бесплатно заблокировать доступ к сайтам в Windows путем правки файла hosts.

    How to Edit the Hosts File in Windows

    Can be useful for anyone in IT

    The hosts file is a text-based file located in the same place in all modern Windows versions. Most people don’t ever need to get into it, but if you do, you’ll need to know how to open and edit the hosts file.

    However, in some versions of Windows, editing the hosts file directly isn’t allowed. In fact, you’ll get an error if you try to save the changes. Fortunately, there’s a simple tip you can use to edit the hosts file in Windows 10, 8, 7, Vista, or XP.

    What Does The Hosts File Do?

    The purpose of the hosts file was originally to be what DNS servers do now – map friendly domain names to unfriendly IP addresses.

    It’s much easier to remember a domain name like YouTube.com than an IP address like 172.217.1.238. Instead of having to type the IP address into the address bar each time you want to watch YouTube videos, you can just enter the domain name, and the DNS server your device is using will map the name to the right address so you can get to the webpage a lot easier.

    The hosts file, since it serves as a sort of DNS server, works the same way. You can enter an IP address that a domain name should be resolved to. In other words, you could order your computer to load a different IP address than the DNS server would, essentially letting you do a few cool things.

    Why Edit The Hosts File?

    One reason to edit the hosts file is if you want a super basic way to block websites from loading on your computer. Enter an invalid or wrong IP address for the site you want to block, and each time you try accessing it, the hosts file will load the IP address you chose. Depending on what you picked, it might completely block the website.

    You can use the same technique to make the hosts file block malicious sites. There are even lists of hosts file entries (such as this one) you can download and import into your hosts file to block hundreds of malicious sites or ads.

    Another use for the hosts file is to speed up your web browsing. If the DNS server you’re using is down or not working quickly enough, manually entering the IP address and domain name mappings in your hosts file lets your computer find those addresses nearly instantly instead of relying on the DNS server.

    Tip: Learn how to use alternate DNS servers to get faster internet access.

    Windows Hosts File Location

    You need to know where to go to find the hosts file before you can open it for editing. This is the hosts file location in Windows 10 through Windows XP:

    C:\Windows\system32\drivers\etc

    How To Edit The Hosts File

    The hosts file is a text file, meaning that you need a text editor to make changes to it. However, since the hosts file is super basic and doesn’t need to deal with hyperlinks, images, etc., you can use a basic text editor (i.e., there’s no need to use a full-fledged editor like Microsoft Word).

    Читайте также:  Как правильно удалить старую windows

    Opening The Hosts File

    Let’s start with simply opening the hosts file. We’ll use Notepad, which is built into Windows 10 down through Windows XP.

    • Open the Run dialog box by holding down the Windows key and then pressing R once.
    • Type notepad and then press Enter to open the program.

    • Go to File >Open.
    • In the file name text box at the bottom, type (or copy and paste) the hosts file location shown above and then press Enter.

    • Select the menu to the right of the text box to change Text Documents (*.txt) to All Files (*).

    • Double-click hosts from the list of files to open the hosts file for editing in Notepad.

    Editing The Hosts File

    There are a few examples in the hosts file to show you how to format your entries. You have to put the IP address first followed by the domain name, and the two have to be separated by at least one space (a tab is a good way to format them).

    Here are some examples:

    127.0.0.1 www.google.com
    13.249.79.104 www.bing.com

    As you can see in the image above and read from the directions in the hosts file, the # symbol is used as a comment, meaning that anything that follows it is avoided. This is why the two example lines we give above are useful in this hosts file; they’re not being followed by that symbol.

    If you want to block websites with the hosts file, such as YouTube, Amazon, Google, Reddit.com, etc., you can enter a false IP address like 0.0.0.0.

    Note: When you enter the URL of the site you want to associate with a specific IP address, be sure to exclude the beginning part and only type the subdomain, such as www or whatever it happens to be for the site you’re adding.

    Saving The Hosts File

    Here’s how we’ll save the hosts file to make sure it works no matter which operating system you use, which text editor you picked, or how your Windows settings are configured:

    • Go to File >Save As.
    • Change the Save as type option to All Files (*).
    • Rename the file to hosts.backupfile, and then save it to your desktop.

    • Close Notepad and then find the hosts file you just created on the desktop. You want to delete the .backupfile part of the name and leave only hosts (with no period or text after the word).

    • After you do that, click away from the file to something else on the desktop, and confirm the name change when asked.
    • Copy the hosts file.
    • Open the hosts file location you had open before (the etc folder).
    • Paste the hosts file you copied from the desktop, and confirm any overwrite prompts if you see them.

    Founder of Help Desk Geek and managing editor. He began blogging in 2007 and quit his job in 2010 to blog full-time. He has over 15 years of industry experience in IT and holds several technical certifications. Read Aseem’s Full Bio

  • Оцените статью