Что такое hosts linux

What is the Purpose of /etc/hosts File in Linux

The /etc/hosts file is an integral part of the Linux system. But what is it used for?

The /etc/hosts file in Linux or any other operating system is used to map connections between IP addresses and domain names.

Quite a generic answer right? Well, this guide is going to get some feet deeper so everyone can benefit from its offering.

What is the /etc/hosts file in Linux?

In the earlier days of networking, the /etc/hosts file was used to translate the IP addressed (8.8.8.8) to human-readable form (www.google.com) and over time it lost its relevance. In modern systems, the whole process of resolving domain names is done through DNS (Domain Name System).

Then why do we still get the hosts file in every operating system?

Rarely but still being used in given cases:

  • When you want to block certain websites.
  • It can be used as a backup in the case when DNS is broken.
  • You can also use it as a local DNS server.

You can think of many other tasks such as blocking ads, enhancing local firewalls, and many other tasks that involve the usage of IPs and DNS!

So now it’s time for some practical examples of how you can utilize the /etc/hosts file.

Use the /etc/hosts file to redirect URLs

The hosts file needs two components to work: domain name and IP.

So what I’m going to do is use the DNS of itsfoss and will redirect it to the IP of LHB.

For that, I’ll be using the ping command to find the IP of LHB:

use ping command in linux

Now, let’s open the hosts file (I’m using the nano text editor here):

how to redirect url in linux

It is considered good practice to have both!

Now, when I pinged itsfoss, it is being redirected to the IP of Linuxhandbook:

traffic has been redirected to different IP in linux

You can use this method for migrating your website from one server to another. Before you actually change the DNS of the website to the new server, you make all the changes on the new server which is accessible through the domain name on your system.

Gridpane uses this trick for migrating WordPress websites.

Block unwanted websites using the /etc/hosts file

So what I’m going to do here is assign my local domain to the sites that I no longer want to use!

For example, I’ll be blocking Facebook! So let’s get the IP address of Facebook:

check ip using ping command in linux

Now, let’s open the hosts file:

block specific website in linux using the hosts file

And when I used the browser to access Facebook, it showed me this:

Create Website shortcuts using the /etc/hosts file

In this example, I’ll be creating a shortcut for Linuxhandbook named lhb.com .

The first step will be similar to what I explained earlier (getting the IP of a domain):

Читайте также:  Linux команда вывести справку

use ping command to check connectivity of domain

Now, let’s modify the hosts file by the given command:

And make changes as given:

create website shortcuts using hosts file in linux

Once you’re done, you put it to the test. I’m using the ping command with a recently made shortcut.

how to create url shortcuts using the hosts file in linux

As you can clearly see, there’s no difference between the IP of the original domain and the shortcut.

Wrapping Up

In this tutorial, I explained the purpose behind having a hosts file and some examples of how you can tweak DNS settings to suit yourself using the hosts file.

And if you still have any queries, the comments section is open for discussion.

Источник

Файл hosts в Linux

Система доменных имен DNS используется для определения, какой IP принадлежит к нужному домену в сети интернет. Когда какой-либо программе понадобится обратиться к сайту по его доменному имени, операционная система отправляет к DNS-серверу запрос, чтобы узнать, по какому IP ей дальше передавать пакеты. Но так происходит не всегда. Например, когда мы обращаемся к домену localhost, то всегда запрос отправляется нашему локальному компьютеру.

Всему причиной файл hosts. Если вы раньше пользовались Windows, то, наверное, уже слышали о таком файле. Там чаще всего он использовался для того, чтобы быстро заблокировать доступ к какому-либо ресурсу. Но применение его гораздо шире. В этой статье мы рассмотрим, как настроить файл hosts в Linux, а также какие возможности он нам предоставляет.

Разрешение доменных имён в Linux

Прежде чем мы перейдём к самому файлу hosts, нужно разобраться, как происходит поиск IP-адреса для доменного имени в Linux. Я говорил, что операционная система сразу же отправляет запрос DNS-серверу, но это не совсем так. Существует определённый порядок поиска, согласно которому он выполняется. Этот порядок установлен в конфигурационном файле /etc/nsswitch.conf

Здесь нас интересует строчка hosts. В ней в порядке очередности записаны службы, которые используются для поиска IP-адреса для доменного имени. Пункт files означает использование файла /etc/hosts, а dns — сервиса доменных имён интернета. Если files расположена перед hosts, это означает, что сначала система попытается найти домен в /etc/hosts, а уже потом по DNS. По умолчанию дело обстоит именно так.

Настройка файла hosts в Linux

Нужный нам файл находится в директории /etc/. Для его открытия можно использовать любой текстовый редактор как в командной строке, так и в графическом интерфейсе, только открывать его нужно с правами суперпользователя. Например, с помощью vim:

Синтаксис файла довольно простой. В нём находится несколько строчек с доменными именами и IP-адресами, которые нужно для них использовать. Каждая из них выглядит вот так:

ip_адрес домен алиас

Обычно первая же строчка создаёт правило для перенаправления всех запросов к домену localhost на локальный IP-адрес — 127.0.0.1:

Также в этом файле по умолчанию размещаются перенаправления для имени вашего компьютера и для IPv6-адресов. Вы можете создать свои настройки для любого нужного домена. Для этого нужно добавить строчку в конец файла. Например, направим все запросы к домену losst.pro на ip 127.0.0.1:

Обратите внимание, что здесь указывается только домен, без протокола. Префикс http или https указывать не нужно, иначе ничего работать не будет. А вот для поддомена www нужно создавать отдельную запись или записывать его в виде алиаса. Например:

127.0.0.1 losst.pro www.losst.pro

Теперь при запросе домена losst.pro будет открываться наш локальный IP. Чтобы вернуть доступ к оригинальному ресурсу, достаточно убрать добавленную строчку. Но вы можете использовать не только локальный адрес, но и любой другой. Это очень удобно, если вы только зарегистрировали домен и доменная зона ещё не успела обновиться, а вы уже хотите работать с новым сайтом. Просто добавьте данные в /etc/hosts и работайте как обычно.

Читайте также:  Realtek linux audio drivers

Выводы

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

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

The /etc/hosts File Complete Guide for Linux

What Is the /etc/hosts File and What is its Purpose?

The /etc/hosts or simply the Hosts file is a plain text file that maps IP addresses with their corresponding hostnames. Primarily, the Hosts file is useful when you are working on a local network of computers. It provides some simple sort of hostname resolution.

The /etc/hosts file is usually useful when we are not using DNS or NIS service for resolving IP addresses. In fact, when DNS did not exist, there were no centralized systems for resolving hostnames. Local networks and computers relied on their Hosts file. This file holds the entries for all the known hostnames and their corresponding IP addresses.

After DNS appeared on the scene, computers did not need this file and started using the DNS service for fetching hostnames. Despite these advances, the Hosts file is still relevant on modern operating systems.

What will we Cover?

In this guide, we will see what a Hosts file in Linux is, some use cases of this file, and an application of this file based on the use cases.

Use Cases of the Hosts File

We can assign a domain name to an IP address using the Hosts file. However, these changes are local and will work on the local computer.

The Hosts file is still relevant today, there are some specific use cases for the Hosts file as mentioned below:

  1. We have built a website, but it is not live on the web since we have not registered the domain name for it. However, if we have a registered IP address from our hosting, we can map this IP to a dummy or non-existing domain name and continue building our website. Similarly, in a software testing environment, many web applications run on the local hosts address i.e. addresses of the type 127.0.0.1. Again, we can manage this using the Hosts file.
  2. In case we have migrated our website from one hosting to another one and we want to check the new hosting performance, we can connect our domain to the new hosting without closing our old hosting account. In this way, we can see how our website is loading from the new hosting.
  3. Suppose you want to block a website, like blocking Facebook on an educational system. We can easily do this by mapping the target domain name to an invalid address IP like 0.0.0.0. This will create a loopback. This is usually helpful for blocking non-educational websites in universities or blocking mature content for kids.
  4. When edited in a proper manner, the Hosts file can operate as a security firewall for a system.

Format of the /etc/hosts File

The Hosts file is located inside the /etc folder. The entries of the file are per line basis. For instance, every single line consists of a hostname followed by its IP address:

Читайте также:  Установка kali linux usb persistence

The IP addresses used here are either IPv4 or IPv6. These addresses and hostnames maintain a distance of any number white space or a distance of a tab character.

On all operating systems, the Hosts file has the same format. Let us see the contents of the file on a Linux system:

# The following lines are desirable for IPv6 capable hosts
:: 1 ip6-localhost ip6-loopback
fe00:: 0 ip6-localnet
ff00:: 0 ip6-mcastprefix
ff02:: 1 ip6-allnodes
ff02:: 2 ip6-allrouters

The Hosts file contains the entries for both the IPv4 and IPv6 addresses.

Application of the Hosts File

As mentioned earlier, we can use the Hosts file for blocking a domain. Let us take the case of blocking Youtube. Open the file:

Use the tab character to insert space between the IP address and its corresponding domain name.

Now, save and close the file. Open any web browser and try to navigate to youtube and see what happens:

We can see youtube.com is blocked and we are getting an ‘Unable to connect’ message. To unblock the site, we have to simply remove the above entry from the /etc/hosts file.

Access Control Files

Besides the plain Hosts file, we also have a /etc/hosts.allow file and a /etc/hosts.deny file.

These files, referred to as hostess access files, are used by TCP wrappers. These files decide whether a client machine can connect to a host.

When a TCP wrapped service gets a client request, it performs the actions below:

  1. Refer to the hosts.allow file: it sequentially reads this file and executes the first rule stated for that service.
  2. Refer to the hosts.deny file: it sequentially reads this file and if a matching rule is found, it does not accept the connection request. Otherwise access is granted to the requesting service.

The hosts.allow file decides which IP addresses can connect to a host. The /etc/hosts.deny file is used in conjunction with it.

Security Issues of the Hosts File

Although the Hosts file looks like a simple file, in some cases, for example, on Windows systems, malware like adware or spyware modifies the Hosts file to take the users to malicious websites.

If you are unsure about the health of your Hosts file, you can use Lynis system auditor for Linux. Lynis has its built-in test build for checking the security strength of your Linux system.

Also, try to keep the Hosts file at a minimum length. If you have too many systems declared inside the Hosts file, you should consider placing them in a different DNS zone.

Conclusion

The Hosts file is an old file on Linux, but still, it is a powerful utility. Right from local name resolving, it is an important part of many software and their development process. In this article, we have seen a basic introduction to the Hosts file in Linux. We have also shown how to block a website using the Hosts file. Also, we can use it to block banners, adware, and other third party page counters.

After reading this article, you should now know how to use the Hosts file for managing DNS queries as per our requirements.

About the author

Ali Imran Nagori

Ali imran is a technical writer and Linux enthusiast who loves to write about Linux system administration and related technologies. You can connect with him on LinkedIn
.

Источник

Оцените статью
Adblock
detector