Как добавить запись в файл hosts windows 10 через командную строку

Для внесения изменений в файл hosts в операционной системе Windows 10 необходимо выполнить следующие шаги:

1) Создать резервную копию файла C:\Windows\System32\drivers\etc\hosts, сохранить его в любом месте. Так как изменения будут вноситься в этот файл.

2) Запустить текстовый редактор Блокнот от имени Администратора:

 

3) Нажать на меню Файл -> Открыть.

В строке адрес ввести: C:\Windows\System32\drivers\etc\hosts

 

Нажать на клавишу Enter, в появившемся окне выбрать «Блокнот» и нажать «ОК«.

 

Откроется файл hosts.

4) Существующие строки можно не удалять, а добавить необходимые:

178.159.245.54 vashdomen.by www.vashdomen.by

5) Поле этого необходимо нажать меню Файл -> Сохранить.

 

Чтобы убедиться в том, что настройка выполнена верно и сайт будет открываться именно с необходимого нам сервера, необходимо «пропинговать» домен.

Сделать это можно с помощью командной строки Windows. Для запуска командной строки необходимо:

Нажать комбинацию клавиш Windows+R на клавиатуре вашего компьютера. В открывшемся окне прописать cmd и нажать кнопку «ОК»

 

В командной строке написать команду ping vashdomen.by, где вместо vashdomen.by впишите доменное имя Вашего сайта и нажмите «Enter»

 

В случае, если IP-адрес при ответе на запрос ping верный — необходимо открыть приватное окно браузера и проверить работу сайта на  указанном сервере.

Внимание! После того как все работы завершены, то есть проверки выполнены. Рекомендуем восстановить файл C:\Windows\System32\drivers\etc\hosts к исходному состоянию. Удалить внесенные изменения либо восстановить его из копии, которую создали на шаге 1. 

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

А если в файл hosts внести запись, в которой адресу сайта в сети Интернет устанавливается в соответствие локальный IP-адрес 127.0.0.1 (Localhost), можно таким образом заблокировать доступ к этому сайту.

Начиная с Windows 2000 файл hosts по умолчанию располагается на локальном диске с операционной системой по адресу C:\Windows\System32\drivers\etc (если система установлена на диск С).

расположение файла hosts в windows

Для редактирования hosts в операционной системе Windows 10 необходим любой текстовый редактор, в том числе встроенные в Windows Блокнот или WordPad, запущенный с привилегиями администратора, или специальная программа. Сетевой адрес и соответствующее ему доменное имя записываются в одной строке, между записями ставится один или несколько пробелов. Значком решетки # помечаются комментарии.

Далее рассмотрим несколько способов редактирования файла hosts в операционной системе Windows 10.

1 способ. Изменение hosts c помощью командной строки.

Открыть на редактирование файл hosts с возможностью сохранения изменений можно используя командную строку. Открыть ее мы можем воспользовавшись поиском. Вводим в поле поиска cmd и запускаем командную строку от имени администратора.

Затем в поле командной строки вводим команду:

notepad C:\Windows\System32\drivers\etc\hosts

где notepad наименование программы (Блокнот) а C:\Windows\System32\drivers\etc\hosts — путь к файлу hosts (если система установлена в другой раздел, укажите букву того раздела, на который установлена система) и жмем Enter.

команда для открытия файла hosts

2 Способ. С помощью Блокнота из учетной записи администратора.

Как было сказано выше, для редактирования файла hosts требуются права администратора. Учетная запись администратора по умолчанию отключена в Windows. Чтобы ее включить нужно запустить командную строку от имени администратора.

запуск командной строки от имени администратора

В окне командной строки вводим команду net user Администратор /active:yes и затем жмем клавишу Enter.

(включить учетную запись администратора

Появится отчет об успешном выполнении команды.

команда выполнена успешно

После чего входим под вновь созданной учетной записью администратора. Под администратором можем беспрепятственно вносить изменения в файл hosts и сохранять изменения. Переходим в папку, расположенную по адресу C:\Windows\System32\drivers\etc, и из контекстного меню, вызванного правой клавишей мыши, выбираем пункт «Открыть с помощью».

открыть с помощью

Затем выбираем программу, которой хотим открыть (например Блокнот), и жмем «ОК».

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

Или переходим в папку по адресу C:\Windows\System32, находим в ней файл notepad и запускаем его от имени администратора, нажав соответствующий пункт контекстного меню.

запуск от имени администратора

В открывшемся окне редактора жмем «Файл» → «Открыть».

блокнот открыть файл

Далее указываем путь к файлу hosts (C:\Windows\System32\drivers\etc) и жмем открыть.

открыть hosts в блокноте

4 способ. С помощью программы Hosts File Editor.

Еще один способ — использование специальных программ для редактирования hosts. Одна из таких программ Hosts File Editor. Скачать ее можно по ссылке http://hostsfileeditor.codeplex.com.
После заполнения соответствующих ячеек таблицы следует нажать «Save».

hosts file editor

Можем из программы Hosts File Editor открыть текстовую версию файла hosts и посмотреть что получилось.

открыть текстовый hosts

hosts в текстовом редакторе

Я очень надеюсь, моя статья помогла Вам! Просьба поделиться ссылкой с друзьями:

Editing the hosts file on Windows 10 using Command Prompt might sound like a techy task, but it’s actually pretty straightforward. You’ll be opening a special file on your computer and editing it to control how your computer looks up website addresses. This can help with things like blocking certain websites or testing your web projects before they go live. In just a few steps, you’ll be able to make the changes you need.

In the following steps, you’ll learn how to use Command Prompt to open and edit the hosts file on Windows 10. These steps will guide you through navigating the system, opening the file with administrative access, making the necessary changes, and saving your edits securely.

Step 1: Open Command Prompt as Administrator

Type «cmd» in the Windows search bar, right-click Command Prompt, and choose «Run as administrator.»

It’s important to run Command Prompt as an administrator, because you’ll need special permissions to edit system files like the hosts file. If you skip this step, you might run into «Access Denied» errors.

Step 2: Navigate to the Hosts File Directory

In Command Prompt, type cd C:WindowsSystem32driversetc and press Enter.

This command will change your current directory to where the hosts file is located. Think of it as telling your computer, «Hey, we’re going to be working over here.»

Step 3: Open the Hosts File with Notepad

Type notepad hosts and press Enter.

This command will open the hosts file in Notepad, allowing you to edit it. Notepad is a simple text editor, making it perfect for this task.

Step 4: Make Your Edits

Add the IP address and domain name you wish to map, formatted like 127.0.0.1 example.com.

Now you can type in the changes you want. For example, if you want to block a website, you can map it to 127.0.0.1, which is the loopback address for your own computer.

Step 5: Save the File

Click «File» in Notepad, then «Save.»

Saving the file is the final step. Make sure you don’t use «Save As» which might change the file format or location.

After completing these steps, your computer will follow the new rules you set in the hosts file. If you mapped a domain to a specific IP address, your computer will follow that instruction next time you try to access the domain.

Tips for Editing Hosts File Windows 10 CMD

  • Always back up the original hosts file before making any changes.
  • Ensure you run Command Prompt as an administrator to avoid permission issues.
  • Be mindful of the format when editing; each entry should be on a new line.
  • Use Notepad or another simple text editor, not a word processor.
  • If changes don’t seem to take effect, try flushing your DNS cache by typing ipconfig /flushdns in Command Prompt.

Frequently Asked Questions

What is the hosts file?

The hosts file is a plain text file used by your computer to map hostnames to IP addresses.

Why do I need to run Command Prompt as an administrator?

You need elevated permissions to edit system files on Windows, and running Command Prompt as an administrator grants you that access.

How do I back up the hosts file?

Simply copy the original hosts file and save it with a different name or in a different location.

What happens if I make a mistake?

A mistake in the hosts file can cause websites to be unreachable or direct to the wrong IP. You can always revert to your backup.

Can I use a different text editor?

Yes, as long as it’s a plain text editor. Avoid using word processors that add formatting.

Summary

  1. Open Command Prompt as Administrator.
  2. Navigate to the Hosts File Directory.
  3. Open the Hosts File with Notepad.
  4. Make Your Edits.
  5. Save the File.

Conclusion

Editing the hosts file on Windows 10 using Command Prompt isn’t as daunting as it seems. It’s a handy trick that can help you manage website access or test new site configurations before they go live. Remember to back up your original file and run Command Prompt as an administrator to avoid any pesky permission issues. Now that you’ve got the hang of it, you can easily tweak your hosts file to suit your needs. If you’re interested in learning more about how to use Command Prompt for other tasks, there are plenty of resources and tutorials out there. So why not dive in and master another tech skill?

Kermit Matthews is a freelance writer based in Philadelphia, Pennsylvania with more than a decade of experience writing technology guides. He has a Bachelor’s and Master’s degree in Computer Science and has spent much of his professional career in IT management.

He specializes in writing content about iPhones, Android devices, Microsoft Office, and many other popular applications and devices.

Read his full bio here.

Last Updated :
20 Nov, 2023

The operating system generally uses a host file to establish a connection between domain names and IP addresses before it goes to the domain name servers. However, sometimes it is required to host files on Windows, MacOS, and Linux to prevent any malicious attack. 

How-to-Edit-Your-Hosts-File-Mac-Linux-or-Windows-1011

In this article, hands-on practice is demonstrated for a better understanding of editing the host file on Windows, MacOS, Linux

What is a Host file?

A host file is a plain text file on a computer that maps hostnames to IP addresses. It establishes a connection between Domain Names and IP addresses. This file helps in local network configuration and can be used to block or redirect websites by associating them with different IP addresses.

Why you should edit the Host File?

You should edit the Host File for different reasons, It allows users to block specific websites, redirect sites to different addresses, or test website changes before they go live. It’s a simple way to control internet access and manage network configurations on a local level without relying on external DNS servers. 

Prerequisite – How to Show Hidden Files and Folders in Windows 10 

How To Edit Your Hosts File On Windows 10 and 11?

There are 2 different standard methods to edit Host file in Windows:

  • Methode 1: Using Notepad to host files in Windows
  • Methode 2: Using PowerToys to host files in Windows

Let’s go through both methods for Edit Hosts file on Windows

Methode 1: Edit Your Hosts File On Windows Using the Notepad 

Step 1: Go to the start menu on the desktop and type the Notepad and press Enter button

How to Edit Your Hosts File on Windows - method 1 - step 1

 

Step 2:  Then open Notepad -> File -> Open to open the Hosts file

How to Edit Your Hosts File on Windows - method 1 - step 2

 

Step 3: Now you need to go to system c disk and go to Windows> System32 > drivers > etc and Select All Files on the right side 

How to Edit Your Hosts File on Windows - method 1 - step 3

 

Step 4: Following this, you will now see the host file and click the entry for the open file in Notepad

How to Edit Your Hosts File on Windows - method 1 - step 4

 

Step 5: Now our file ready to EDIT

How to Edit Your Hosts File on Windows - method 1 - step 5

 

Now, your Hosts file is ready to edit in just 5 simple steps.

Methode 2: Edit Your Hosts File On Windows using PowerToys

Step 1: Hit the Start on the desktop and type the Microsoft Store and press Enter button

How to Edit Your Hosts File on Windows - method 2 - step 1

 

Step 2: You need to search the Microsoft PowerToys and click the install button from the Microsoft Store.

How to Edit Your Hosts File on Windows - method 2 - step 2

 

Step 3: Once the installation is complete, simply click on the PowerToys icon and click the Settings

How to Edit Your Hosts File on Windows - method 2 - step 3

Step 4: Following this, now click on the Hosts File Editor and click on Launch Host File Editor 

How to Edit Your Hosts File on Windows - method 2 - step 4

Step 5: Now simply click on the host file editor, and your Hosts file is ready to Edit

How to Edit Your Hosts File on Windows - method 2 - step 5

How to Edit Hosts File in Linux?

To edit the hosts file in Linux, follow these steps to edit the Linux host files:

Step 1: Open a terminal ( Ctrl+Alt+T )

Step 2: Run Text Editor with Administrative Rights by typing following command, you can replace «nano» with your preferred text editor

sudo nano /etc/hosts

Edit-Hosts-File-in-Linux_1

Step 3: Enter your Admin password.

Step 4: Edit the file entries in the format «IP_address domain_name».

Edit-Hosts-File-in-Linux_2

Step 5: Save the file, Changes are now applied.

How to Edit Hosts File in MacOS?

To edit the hosts file on macOS, follow these steps to edit the MacOS host files:

Step 1: Open the Terminal application.

Step 2: Run Text Editor with Administrative Rights by typing following command, you can replace «nano» with your preferred text editor

sudo nano /etc/hosts

Edit-Hosts-File-in-MacOS_1

Step 3: Enter your Admin password.

Step 4: Edit the file entries in the format «IP_address domain_name«.

Edit-Hosts-File-in-MacOS_2

Step 5: Save the file( Ctrl+O ) and exit the text editor ( Ctrl+X ).

By following these simple steps, we successfully edited the host file available on Windows, MacOS, Linux to prevent any malicious attack. 

Also Read

  • What is Local Host?
  • Changing Host IP Address in Flask
  • Create a shared Folder between Host OS and Guest OS
  • Difference Between Host and Guest Operating System

This guide shows you how to edit hosts file in Windows 10 and Windows 11 easily without any additional system tools. The hosts file is an important system file that maps the host/website names with its IP addresses. Basically, it translates the hostname to IP and vice versa. So browsing and accessing network websites and shares by the name becomes easy by avoiding DNS server requests or remembering the relevant IP addresses.

We can manually edit DNS names and IP addresses for specific websites in the hosts file which will be helpful in several ways. The hosts file is a simple text file without any file extensions.

Edit Hosts File

We used to modify this file by ‘edit’  DOS command in earlier Windows operating systems, but the edit DOS command is not included in Windows 11 and 10/8.1 anymore. You will get the following error message when you try the edit command in recent Operating Systems.

“ ‘edit’ is not recognized as an internal or external command, operable program or batch file.”

edit command error

This is because of edit DOS command requires 16-bit QBASIC.EXE which will not work on the 64 Bit versions of Windows Operating Systems. So how to edit the hosts file here? we can use the built-in Notepad program for this purpose.

In Windows Operating Systems, the hosts file is located here,

C:\Windows\System32\Drivers\etc

host file location in windows 10

C – is the drive where Windows OS is installed in most cases. If your OS is installed in a different partition, then you need to change this letter.

Make sure you have administrative access/privilege on the computer before attempting to modify the hosts file.

Important Note: Some of the Antivirus software including Microsoft Security Essential (Windows Defender) will not allow modifying hosts file as a security precaution. This is to prevent hosts file modification by any virus, spyware or malware threat. If you experience this, you need to disable the Antivirus software temporarily or exclude the hosts file from the protection.

Method-1:

1) Open the command prompt as administrator.

Search ‘cmd’ on Windows 11 or 10 and right-click on the Command Prompt and select ‘Run as administrator.’ (This is an important step).

Open Cmd As Administrator In Windows 11

2) It will probably open from C:\Windows\System32, then type ‘cd drivers’ and ENTER.

Now type ‘cd etc’, ENTER as shown below. This is to go to the location where the host file is located.

Browse the location

3) Make sure you are in the correct folder path, it should be C:\Windows\System32\Drivers\etc. Type ‘notepad hosts’ to open the file in notepad.

Open Notepad In Cmd

4) We assume that you know the content of the file. Type the IP address of the domain/hostname and DNS name of it. You can see the examples in the same file.

Here is an example, Let’s say if I need to block Facebook on a PC, I can enter the wrong IP address and map it to facebook.com as we showed here.

Edit Hosts File In Windows 11

Once you have modified the file with appropriate settings, click Save from File menu.

Important Note: If you haven’t opened the notepad from the ‘Run as Administrator’ command prompt, then you can’t save the Hosts file in the above case.

Method-2:

This could be the easiest way to edit hosts file in Windows 11 without typing any commands in the command prompt.

5) Search for the notepad and open it with administrative access. Right-click and ‘Run as Administrator’.

Open Notepad

6) Navigate to the hosts file location. It’s under C:\Windows\System32\Drivers\etc.

Change the file format to ‘All files,’ then open the hosts file and modify the settings as you want.

Open The Hosts File In Notepad

7) Save the file once changes are done as we did in method 1.

Since these changes are related to DNS, it is better to clear the DNS cache before checking the impact of hosts file modification.

Open command prompt, and type;

ipconfig /flushdns

Why Modify Hosts file in Windows OS or other Operating Systems?

This is an advanced user action and most of the time you do not need to touch the hosts file. But, here are the possible scenarios you may need to modify.

  1. Block a website by giving the wrong IP. So, the PC will look for wrong IP for particular website and ultimatly it will not work.
  2. You are testing a website which was migrated to a different host. Before changing the public DNS entries, you can modify the hosts file on your local PC with the new IP and test.
  3. Unintentional changes by any programs or virus attacks to the hosts file. In this case, you need to clear or edit the hosts file to default settings.
  4. Manipulate the DNS entries. If you need to resolve a name to IP which can’t be done by the DNS servers, the modifying the hosts file is the only one option.

We hope this guide is helpful in editing the hosts file in Windows 11/10 or earlier Operating Systems.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как подключить проводные наушники с микрофоном к ноутбуку windows 10
  • Какие файловые системы поддерживаются операционной системой windows 8
  • Nvidia vga driver for windows 10 64 bit notebook
  • Команды в cmd для windows 10 чтобы напугать
  • Behringer um2 driver windows 10