Dns lookup from linux

10 примеров использования команды dig для просмотра параметров DNS (DNS Lookup) в Linux

Итак, что такое dig?

dig (англ. слово «копать», а формально — сокращение от «domain information groper») — утилита (DNS-клиент), предоставляющая пользователю интерфейс командной строки для обращения к системе DNS. Позволяет задавать различные типы запросов и запрашивать произвольно указываемые сервера. Является аналогом утилиты nslookup.

Утилита dig входит в стандартный комплект DNS сервера BIND.

1. Простой вывод команды dig (для понимания вывода, без доп.параметров )

Когда вы задаете имя домена в команде dig по-умолчанию вы получаете A-запись домена (ip-адрес сайта (домена) который мы запрашивали) как показано на листинге ниже

В примере можно увидеть A-записи домена ya.ru в разделе ANSWER SECTION

Давайте рассмотрим разделы данного вывода подробней:
— HEADER (заголовок): показывает версию dig, глобальные опции используемые с командой и другую дополнительную информацию
— QUESTION SECTION (секция запроса): Показывает наш запрос, то бишь мы запросили показать A-запись (команда dig без параметров) для домена ya.ru
— ANSWER SECTION (секция ответа): Показывает ответ полученный от DNS, в нашем случае показывает A-запись для ya.ru
Последняя секция это статистика по запросу (служебная информация) — время выполнения запроса, имя DNS-сервера который запрашивался, когда был создан запрос и размер сообщения

Так же можно выполнить опрос конкретного DNS-сервера:

Результат вывода дополняется еще двумя секциями:
AUTHORITY SECTION: Показывает имена DNS-серверов обработавших наш запрос
ADDITIONAL SECTION: Показывает ip-адреса этих DNS-серверов (из секции AUTHORITY SECTION)

2. Вывод только секции ANSWER SECTION

В большинстве случаев требуется только ip адрес домена, то бишь вывод секции «ANSWER SECTION»
Для этого существуют следующие ключи:
-+nocomments — отключает линию комментариев
-+noauthority — отключает секцию «AUTHORITY SECTION»
-+noadditional – отключает секцию «ADDITIONAL SECTION»
-+nostats – отключает секцию статистики
-+noanswer – выключает секцию ответа (ANSWER SECTION)

Можно сделать проще, существует ключ +noall, который выключает все секции. Таким образом мы используем ключ +noall и добавляем ключ +answer, уменьшая длину команды

3. Запрос MX-записи

Для запроса MX-записи домена мы используем одноименный аргумент командной строки (MX)

Этот же запрос можно выполнить с ключом -t (тип)

4. Запрос NS-записи

По аналогии с предыдущим пунктом, используем аргумент NS

Читайте также:  Как отключить оповещения брандмауэра windows 10

Вы также можете использовать ключ -t для указания типа запроса

5. Просмотр всех типов DNS-записей

Для этого используется ключ ANY

Также допустим ключ -t

6. Краткий вывод команды dig

Допустим чтобы просмотреть только ip-адрес, без лишней информации, используем опцию +short

Вы также можете вывести информацию по любому виду информации с ключем +short
Пример:

7. Просмотр информации об обратной зоне домена (PTR)

Для просмотра обратной зоны необходимо использовать ключ -х
Для примера, мы хотим узнать имя домена по айпи-адресу 77.88.21.3

Для вывода полной информации убираем ключ +short

8. Использование конкретного DNS-сервера для выполнения запроса

Для использования конкретного DNS-сервераиспользуется запись вида — @dnsserver, где dnsserver это или имя или ip-адрес DNS-сервера
Данный пример мы рассмотрели в п.1

9. Объемный запрос (запрос информации сразу о нескольких доменах)

Для запроса информации о нескольких доменах возможно использование текстовых файлов с перечислением доменов.
Создадим файл names.txt с именами доменов:

Далее используем ключ -f для чтения из файла:

Также можно комбинировать тип DNS записи c опцией -f:

Также возможно перечисление доменов непосредственно в командной строке. Для примера узнаем MX-запись для домена ya.ru и NS-запись для домена google.ru:

10. Изменение параметров по умолчанию для команды dig

Например вы хотите, чтобы утилита dig по умолчанию выводила только секцию ответа (ANSWER SECTION).
Для этого необходимо внести в файл .digrc необходимые ключи, в нашем случае +noall +answer:

Таким образом мы рассмотрели мизерную часть этой замечательной утилиты, для тех, кто хочет большего, добро пожаловать в man dig 😉

Источник

Linux / UNIX: DNS Lookup Command

[a] host command – DNS lookup utility. [b] dig command – DNS lookup utility.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 10m

Both commands will allow you to get answer to various dns queries such as the IP address (A), mail exchanges (MX), name servers (NS), text annotations (TXT), or ANY (all) type.

host DNS Lookup Examples

host command is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host command displays a short summary of its command line arguments and options. The syntax is as follows:

Task: Find Out the Domain IP

$ host -t a cyberciti.biz
Sample outputs:

Task: Find Out the Domain Mail Server

$ host -t mx cyberciti.biz
Sample outputs:

Task: Find Out the Domain Name Servers

$ host -t ns cyberciti.biz
Sample outputs:

Task: Find Out the Domain TXT Recored (e.g. SPF)

$ host -t txt cyberciti.biz
Sample outputs:

Task: Find Out the Domain CNAME Record

$ host -t cname files.cyberciti.biz
Sample outputs:

Task: Find Out the Domain SOA Record

$ host -t soa cyberciti.biz
Sample outputs:

Task: Query Particular Name Server

Query ns2.nixcraft.net for the domain called cyberciti.biz:
$ host cyberciti.biz ns2.nixcraft.net
Sample outputs:

Task: Display All Information About Domain Records and Zone

You need to pass the -a (all) option and asking host command to make a query of type ANY:
$ host -a cyberciti.biz
OR
$ host -t any cyberciti.biz
Sample outputs:

Task: Reverse IP Lookup

Type the command:
$ host < IP-Address-Here >
$ host 75.126.153.206
Sample outputs:

Task: Get TTL Information

Type the command as follows:
$ host -v -t
$ host -v -t a cyberciti.biz
$ host -v -t a i.hexindia.net
Sample outputs:

If you run the same command again, you’ll notice that the TTL number (1866) reduced.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

dig DNS Lookup Examples

dig (domain information groper) is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. hos dns lookup tool have less functionality than dig.

Examples

The basic syntax is:

Task: Trace Domain Delegation Path

See how domains are resolved using root servers i.e. turn on tracing of the delegation path from the root name servers for the name being looked up. When tracing is enabled, dig makes iterative queries to resolve the name being looked up. It will follow referrals from the root servers, showing the answer from each server that was used to resolve the lookup:
$ dig +trace cyberciti.biz
Sample outputs:

Task: Get Only Short Answer

A quick way to just get the answer is to type the following command:
$ dig +short cyberciti.biz
Sample outputs:

Task: Display All Records

$ dig +noall +answer cyberciti.biz any
Sample outputs:

Task: Reverse IP Lookup

Type the following command:
$ dig -x +short < IP-Address-here >
$ dig -x 75.126.153.206 +short
Sample outputs

Task: Find Domain SOA Record

$ dig +nssearch cyberciti.biz
Sample outputs:

Task: Find Out TTL Value Using dig

$ dig +nocmd +noall +answer < TYPE >< example.com >
$ dig +nocmd +noall +answer a cyberciti.biz
Sample outputs:

Run again, enter:
$ dig +nocmd +noall +answer a cyberciti.biz
Sample outputs:

See also:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Cool work…
Love this one…

Good Work! Nice to see all the main DNS troubleshooting commands clubbed in one page. It will be really helpful for the newbies…

PS: Found one typo in the following command:

Task: Get TTL Information


$ host -t -t a cyberciti.biz
$ host -t -t a i.hexindia.net

It should be host -v -t a cyberciti.biz

Thanks for the heads up!

Super useful, Vivek. I’m definitely bookmarking this page.

FWIW, I find ‘whois IP number’ really useful for determining who owns a given IP number (helpful when tracking abuse). An example:

$ whois 75.126.153.206
[Querying whois.arin.net]
[Redirected to rwhois.softlayer.com:4321]
[Querying rwhois.softlayer.com]
[rwhois.softlayer.com]
%rwhois V-1.5:003fff:00 rwhois.softlayer.com (by Network Solutions, Inc. V-1.5.9.5)
network:Class-Name:network
network:ID:NETBLK-SOFTLAYER.75.126.128.0/19
network:Auth-Area:75.126.128.0/19
network:Network-Name:SOFTLAYER-75.126.128.0
network:IP-Network:75.126.153.200/29
network:IP-Network-Block:75.126.153.200-75.126.153.207
network:Organization;I:SoftLayer Technologies, Inc.
network:Street-Address:1950 Stemmons Freeway Suite 2043
network:City:Dallas
network:State:TX
network:Postal-Code:75207
network:Country-Code:US
network:Tech-Contact;I:sysadmins@softlayer.com
network:Abuse-Contact;I:abuse@softlayer.com
network:Admin-Contact;I:IPADM258-ARIN
network:Created:20070218
network:Updated:20091220
network:Updated-By:ipadmin@softlayer.com

%referral rwhois://root.rwhois.net:4321/auth-area=.
%ok

Hi there.. Firstly thanks for this great guide. I need some guide to point me my error. I have setup DNS on server but I didnt register the domain yet. Just need confirmation before I register my domain. I run command below and get an error.

# host 110.159.193.37
Host 37.193.159.110.in-addr.arpa. not found: 3(NXDOMAIN)
***********************************
# host -t A don.my
don.my has address 110.159.193.37
# host -t ns don.my
don.my name server ns1.don.my.
# host -t txt don.my
don.my has no TXT record
# host -t soa don.my
don.my has SOA record ns1.don.my. root.don.my. 2013042202 3600 1800 604800 86400
# host -t any don.my
don.my has SOA record ns1.don.my. root.don.my. 2013042202 3600 1800 604800 86400
don.my name server ns1.don.my.
don.my has address 110.159.193.37

I tried to setup email server and dns server on the same machine. Is there any step that I missed in DNS setup?

Thanks in advance.

# dig -x 110.159.193.37

; <> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6_4.4 <> -x 110.159.193.37
;; global options: +cmd
;; Got answer:
;; ->>HEADER RozaCam458 Jun 4, 2016 @ 5:21

Hi cyberciti
thanks for share good tip for this topic.

Источник

Читайте также:  Microsoft windows лицензионное соглашение
Оцените статью