Как включить строки в resolv.conf, которые не будут потеряны при перезагрузке?
Содержание:
файл host.conf
В файле host.conf содержатся опции программы-определителя (см.
следующую таблицу). Каждая опция может иметь несколько полей, отделенных друг от друга пробелами
или знаками табуляции. Для ввода комментария в начале строки нужно ставить знак
#. Опции указывают определителю, каким сервисом пользоваться
Важное значение имеет порядок
следования опций. Определитель начинает обработку с первой из указанных опций и переходит по очереди
к следующим
Файл host.conf находится в каталоге
/etc вместе с другими файлами конфигурации.
order | Задает последовательность методов преобразования именhosts Проверяется наличие имени в локальном файле /etc/hostbind Запрашивается адрес у сервера имен DNSnis Для получения адреса используется база данных центра сетевой информации (NIS)alert Проверяет наличие в локальной системе адресов удаленных узлов, пытающихся получить к ней доступ; устанавливается и отменяется ключевыми словами on и off |
nospoof | Подтверждает правильность адресов удаленных узлов, пытающихся получить доступ к локальной системе |
trim | Удаляет имя домена из полного имени и проверяет наличие только хост-имени. Позволяет использовать вместо IP-адреса не полное имя хост.домен.расширение, а просто хост-имя, указанное в файле hosts. |
multi | Позволяет хост-машине иметь несколько IP-адресов в локальном файле hosts. Включается и выключается ключевыми словами on и off |
В следующем примере, где представлен файл host.conf,
опция order дает программе-определителю указание искать имена в
локальном файле /etc/ hosts, а в случае неудачи направлять запрос
на сервер имен. Не допускается использование нескольких адресов системы.
# host.conf file # Lookup names in host file and then check DNS order bind host # There are no multiple addresses multi off
Удаление resolvconf в Ubuntu старше 12.04
Для демонстрации используется Ubuntu 16.04, начиная с версии 12.04 данный дистрибутив использует утилиту resolvconf, которая контролирует DNS автоматически. Для рабочих станций данная утилита очень полезна, для серверов — нет.
Видим в файле информацию о том, что он заполняется автоматически и править конфигурацию вручную нельзя. Поскольку нас это не вполне устраивает — удаляем утилиту (на рабочих станциях вносить изменения DNS можно редактируя файлы head, base и tail в каталоге /etc/resolvconf/resolv.conf.d — структура файлов будет рассмотрена в одной из следующих статей).
Сейчас предупреждения, которое выводилось раньше, нет.
Установка и настройка bind9
Устанавливаем bind9
Конфигурационные файлы располагаются в каталоге /etc/bind. Основные файлы: named.conf и named.conf.local
Общая форма конфига bind9 представлена в файле db.local
Конфигурации также представлены в named.conf.default-zones
Здесь можно увидеть записи двух типов:
zone «localhost» { type master; file «/etc/bind/db.local»; };
zone «127.in-addr.arpa» { type master; file «/etc/bind/db.127»; };
Первая запись характеризует прямое преобразование — доменного имени в IP-адрес, вторая — обратное преобразование — IP-адреса в доменное имя.
Дальнейшие изменения вносим в файл named.conf.local
zone «example.com» { type master; file «/etc/bind/example.com.zone»; };
$TTL 3600 @ IN SOA localhost localhost ( 20170211001 ;серийный номер 3600 ;время обновления 3600 ;повторная попытка запроса обновления от мастера 3600 ;время истечения срока действия 3600 ;кэширование TTL )
IN NS server01.example.com. IN A 192.168.11.76 alias IN CNAME server01
При использовании FQDN — в NS записи — (полностью определенного доменного имени) точка в его конце обязательна.
Серийный номер — чаще всего дата + порядковый номер изменеий за день, инкрементировать число нужно каждый раз обновляя зону для того чтобы слэйв сервера DNS могли среагировать на то, что информация обновилась и обновить свои записи
Значения времени обновления,повторной попытки запроса обновления от мастера, времени истечения срока действия и кэширования TTL всех указанных параметров можно варьировать, в большинстве случаев используется значение 3600 секунд, в случае большой нагрузки на сервер — при использовании его в публичных местах — значения можно увеличивать для того чтобы уменьшить трафик в сети.
NS запись DNS — запись, определяющая к какому серверу будет происходить запрос при попытке разрешеиня имени или адреса.
А запись DNS — запись согласно которой производится запрос к серверу на наличие файлов сайта.
CNAME запись используется для создания синонимов — при запросе к alias.example.com в данном случае производится обращение к server01.example.com.
В случае если при перезапуске службы ошибок не возникло — конфигурационные файлы составлены корректно
Чтобы проверить корректность работы bind9 заставим сервер обращаться к себе
nameserver 192.168.11.76 domain example.com search example.com
Проверяем (о том, как проверять DNS записи для домена)
В выводе присутсвует адрес 192.168.11.76, что означает, что успешно разрешаются как CNAME, так и A записи).
Пинг есть, значит bind работает корректно
Теперь настроим обратное преобразование
Как и ранее идем в named.conf.local; добавляем следующие строки
zone «11.168.192.in-addr.arpa» { type master; file «/etc/bind/192.168.11.zone»; };
$TTL 3600 @ IN SOA localhost localhost ( 20170211001 ;серийный номер 3600 ;время обновления 3600 ;повторная попытка запроса обновления от мастера 3600 ;время истечения срока действия 3600 ;кэширование TTL )
IN NS server01.example.com. IN A 192.168.11.76 76 IN PTR server01.example.com.
В PTR записи прописывается только последний октет адреса 192.168.11.76, bind добавляет остальные октеты, если пренебречь этим правилом обратное преобразование происходить не будет.
Name Service Switch
This article or section needs expansion.
The Name Service Switch (NSS) facility is part of the GNU C Library () and backs the API, used to resolve domain names. NSS allows system databases to be provided by separate services, whose search order can be configured by the administrator in . The database responsible for domain name resolution is the hosts database, for which glibc offers the following services:
- file: reads the file, see
- dns: the which reads , see
Systemd provides three NSS services for hostname resolution:
- — a caching DNS stub resolver, described in systemd-resolved
- — provides hostname resolution without having to edit , described in
- — provides hostname resolution for the names of local containers
Resolve a domain name using NSS
NSS databases can be queried with . A domain name can be resolved through NSS using:
$ getent hosts domain_name
Note: While most programs resolve domain names using NSS, some may read and/or directly. See .
Alternative DNS servers
To use alternative DNS servers, edit and add them to the top of the file so they are used first, optionally removing or commenting out already listed servers. Currently, you may include a maximum of three lines.
Note: Changes made to take effect immediately.
Tip: If you require more flexibility, e.g. more than three nameservers, you can use a locally caching nameserver/resolver like dnsmasq or unbound. Using a local DNS caching resolver, most likely you will not set the to the actual DNS server but to . See the article for the program you are using for DNS caching.
OpenNIC
# OpenNIC IPv4 nameservers (Worldwide Anycast) nameserver 185.121.177.177 nameserver 185.121.177.53
# OpenNIC IPv6 nameservers (Worldwide Anycast) nameserver 2a05:dfc7:5::53 nameserver 2a05:dfc7:5::5353
Cisco Umbrella (was: OpenDNS)
# OpenDNS IPv4 nameservers nameserver 208.67.222.222 nameserver 208.67.220.220
# OpenDNS IPv6 nameservers nameserver 2620:0:ccc::2 nameserver 2620:0:ccd::2
# Google IPv4 nameservers nameserver 8.8.8.8 nameserver 8.8.4.4
# Google IPv6 nameservers nameserver 2001:4860:4860::8888 nameserver 2001:4860:4860::8844
Yandex
# Basic Yandex.DNS - Quick and reliable DNS nameserver 77.88.8.8 # Preferred IPv4 DNS nameserver 77.88.8.1 # Alternate IPv4 DNS nameserver 2a02:6b8::feed:0ff # Preferred IPv6 DNS nameserver 2a02:6b8:0:1::feed:0ff # Alternate IPv6 DNS
# Safe Yandex.DNS - Protection from virus and fraudulent content nameserver 77.88.8.88 # Preferred IPv4 DNS nameserver 77.88.8.2 # Alternate IPv4 DNS nameserver 2a02:6b8::feed:bad # Preferred IPv6 DNS nameserver 2a02:6b8:0:1::feed:bad # Alternate IPv6 DNS
# Family Yandex.DNS - Without adult content nameserver 77.88.8.7 # Preferred IPv4 DNS nameserver 77.88.8.3 # Alternate IPv4 DNS nameserver 2a02:6b8::feed:a11 # Preferred IPv6 DNS nameserver 2a02:6b8:0:1::feed:a11 # Alternate IPv6 DNS
Yandex.DNS’ speed is the same in all three modes. In «Basic» mode, there is no traffic filtering. In «Safe» mode, protection from infected and fraudulent sites is provided. «Family» mode enables protection from dangerous sites and blocks sites with adult content.
UncensoredDNS
# censurfridns.dk IPv4 nameservers nameserver 91.239.100.100 ## anycast.censurfridns.dk nameserver 89.233.43.71 ## ns1.censurfridns.dk
# censurfridns.dk IPv6 nameservers nameserver 2001:67c:28a4:: ## anycast.censurfridns.dk nameserver 2002:d596:2a92:1:71:53:: ## ns1.censurfridns.dk
CONSUMERS OF NAMESERVER INFORMATION
resolvconfresolvconf/etc/resolvconf/update.d//etc/resolvconf/update-libc.d/dnsmasqpdnsd
libc
resolver/etc/resolvconf/update.d/libc/run/resolvconf/resolv.conf/etc/resolvconf/update-libc.d/
The dynamically generated resolver configuration file
always starts with the contents of
/etc/resolvconf/resolv.conf.d/head
and ends with the contents of
/etc/resolvconf/resolv.conf.d/tail.
Between
head
and
tail
the
libc
script inserts
dynamic nameserver information
compiled from,
first,
information provided for configured interfaces;
second,
static information from
/etc/resolvconf/resolv.conf.d/base.
Specifically, it writes:
- 1)
-
up to three
nameserverlines,
ordered according to
/etc/resolvconf/interface-order,possibly fewer
if one of the addresses is a loopback address and the
TRUNCATE_NAMESERVER_LIST_AFTER_LOOPBACK_ADDRESSenvironment variable is affirmatively set, as discussed in the
ENVIRONMENT VARIABLESsection;
- 2)
-
up to one
searchline containing the combined domain search list from all
«domain» and «search» input lines,
also ordered according to
interface-order(5); - 3)
- all other non-comment input lines.
To make the resolver use
this dynamically generated resolver configuration file
the administrator should ensure that
/etc/resolv.conf
is a symbolic link to
/run/resolvconf/resolv.conf.
This link is normally created on installation of the resolvconf package.
The link is never modified by the
resolvconf
program itself.
If you find that
/etc/resolv.conf
is not being updated,
please check to make sure that the link is intact.
The GNU C Library resolver library isn’t the only resolver library available.
However, any resolver library that reads
/etc/resolv.conf
(and most of them do, in order to be compatible)
should work fine with resolvconf.
Subscriber packages that need to know only when the resolver configuration file
has changed should install a script in
/etc/resolvconf/update-libc.d/
rather than in
/etc/resolvconf/update.d/.
(For example, two packages that install
update-libc.d/
hook scripts are
fetchmail
and
squid.)
This is important for synchronization purposes:
scripts in
update-libc.d/
are run
after
resolv.conf
has been updated;
the same is not necessarily true of scripts in
update.d/.
ENVIRONMENT VARIABLES
/etc/default/resolvconf
- REPORT_ABSENT_SYMLINK
-
If set to «yes» then
resolvconfwill print a message when
/etc/resolv.confis not a symbolic link
to the
resolvconf-generatedresolver configuration file.
Set to «no» to prevent the printing of this message.
The default is «yes». - TRUNCATE_NAMESERVER_LIST_AFTER_LOOPBACK_ADDRESS
-
If set to «yes» then the
libcscript will include
no more nameserver addresses
after the first nameserver address
that is a loopback address.
(In IPv4 a loopback address is any one that starts with «127.».
In IPv6 the loopback address is «::1».) -
The advantage of truncating the nameserver list after a loopback address
is that doing so inhibits unnecessary changes to
resolv.confand thus reduces the number of instances in which the
update-libc.d/scripts have to be run.
When an interface is brought up or down
the local caching nameserver
that listens on the loopback address
is still informed of the change and adapts accordingly;
the clients of the resolver which use the local caching nameserver
do not need to be notified of the change.
A disadvantage of this mode of operation is that applications have
no secondary or tertiary nameserver address to fall back on should
the local caching nameserver crash.
Insofar as a local nameserver crash can be regarded
as an unlikely event,
this is a relatively minor disadvantage.
Set to «no» to disable truncation.
The default is «yes». -
A deprecated synonym for this variable is
TRUNCATE_NAMESERVER_LIST_AFTER_127.
Preserve DNS settings
dhcpcd, netctl, NetworkManager, and various other processes can overwrite . This is usually desirable behavior, but sometimes DNS settings need to be set manually (e.g. when using a static IP address). There are several ways to accomplish this.
- If you are using dhcpcd, see below.
- If you are using netctl and static IP address assignment, do not use the options in your profile, otherwise resolvconf is called and overwritten.
With NetworkManager
To stop NetworkManager from modifying , edit and add the following in the section:
dns=none
might be a broken symlink that you will need to remove after doing that. Then, just create a new file.
Using openresolv
provides a utility resolvconf, which is a framework for managing multiple DNS configurations. See and for more information.
The configuration is done in and running will generate .
Modify the dhcpcd config
dhcpcd’s configuration file may be edited to prevent the dhcpcd daemon from overwriting . To do this, add the following to the last section of :
nohook resolv.conf
Alternatively, you can create a file called containing your DNS servers. dhcpcd will prepend this file to the beginning of .
Or you can configure dhcpcd to use the same DNS servers every time. To do this, add the following line at the end of your :
static domain_name_servers=8.8.4.4 8.8.8.8
Write-protect /etc/resolv.conf
Another way to protect your from being modified by anything is setting the immutable (write-protection) attribute:
# chattr +i /etc/resolv.conf
Use timeout option to reduce hostname lookup time
If you are confronted with a very long hostname lookup (may it be in pacman or while browsing), it often helps to define a small timeout after which an alternative nameserver is used. To do so, put the following in .
options timeout:1
DNS in Linux
Your ISP (usually) provides working DNS servers, and a router may also add an extra DNS server in case you have your own cache server. Switching between DNS servers does not represent a problem for Windows users, because if a DNS server is slow or does not work it will immediately switch to a better one. However, Linux usually takes longer to timeout, which could be the reason why you are getting a delay.
Testing
Use drill (provided by package ) before any changes, repeat after making the adjustments and compare the query time(s). The following command uses the nameservers set in :
$ drill www5.yahoo.com
You can also specify a specific nameserver’s ip address, bypassing the settings in your :
$ drill @ip.of.name.server www5.yahoo.com
For example to test Google’s name servers:
$ drill @8.8.8.8 www5.yahoo.com
To test a local name server (such as unbound) do:
$ drill @127.0.0.1 www5.yahoo.com
RedHat 6.x и Mandrake 6.x
Настройка DHCPcd под RedHat 6.0+ достаточно проста. Все что от вас требуется — запустить панель управления, набрав control-panel.
-
Выбрать «Network Configuration»
-
Щелкнуть на Interfaces
-
Щелкнуть на Add
-
Выбрать Ethernet
-
В Edit Ethernet/Bus Interface выбрать «Activate interface at boot time», а также выбрать «DHCP» как «Interface configuration protocol»
Заметьте, что в RedHat 6.x, вместо вышеупомянутого dhcpcd, Redhat по умолчанию включила DHCP клиент называемый pump. Установочный CD-ROM также содержит и dhcpcd RPM, так что если вы не удовлетворены pump, попробуйте вместо него dhcpcd. После установки dhcpcd (т.е. rpm -i dhcpcd-1.3.17pl2-1.i386.rpm) вам следует сделать несколько .
Дополнительные заметки от Alexander Stevenson <alexander.stevenson@home.com>:
Я не доволен DHCPcd. Что привело меня к работе с «pump», который поставляется с Linux Mandrake 6.0 (и, я полагаю, он также включен в RedHat). Я использую команду:
pump -i eth0 -h hostname
Не имеет значение, какой был указан «hostname», но без него сервер не отвечал бы.
Затем, для отражения изменений я меняю строку в моем скрипте /sbin/ifup; версия по умолчанию не содержит ключ -h , и поэтому она у меня не работала.
По существу, если вы используете linuxconf, и после настройки адаптера на использование «DHCP» он все еще не работает, попробуйте добавить «-h hostname» в строку с pump в скрипте /sbin/ifup. Теперь мой скрипт выглядит так:
... if ; then echo -n "Determining IP information for $DEVICE..." if /sbin/pump -i $DEVICE -h hostname; then echo " done." else echo " failed." exit 1 fi else ... |
Другой, более элегантный путь добавления поля hostname предоставлен Aad van der Klaauw:
Сейчас дома я настраиваю шлюзовую систему, требуется установить MAC адрес и использовать ‘-h hostname’. Поэтому я решил *не* изменять скрипт, а использовать конфигурационный файл. В моем /etc/sysconfig/network-scripts/ifcfg-eth0 я добавил следующее
DEVICE="eth0" MACADDR="00:11:22:33:44:55" DHCP_HOSTNAME="trigger_for_terayon" |
Эти строки пережили обновления системы, и, по моему мнению, это «более правильный» способ.