Ошибка «bash: dig: команда не найдена» (решено)
Содержание:
Understanding the dig Output #
In its simplest form, when used to query a single host (domain) without any additional options, the command is pretty verbose.
In the following example, we’re performing on the domain:
The output should look something like this:
Let’s go section by section and explain the output of the command:
-
The first line of the output prints the installed version, and the queried domain name. The second line shows the global options (by default, only cmd).
If you don’t want those lines to be included in the output, use the option. This option must be the very first one after the command.
-
The next section includes technical details about the answer received from the requested authority (DNS server). The header shows the opcode (the action performed by ) and the status of the action. In this example, the status is , which means that the requested authority served the query without any issue.
This section can be removed using the option, which also disables some other section’s headers.
-
The “OPT” pseudo section is shown only in the newer versions of the utility. You can read more about the Extension mechanisms for DNS (EDNS) here .
To exclude this section from the output, use the option.
-
In the “QUESTION” section shows the query (question). By default, requests the A record.
You can disable this section using the option.
-
The “ANSWER” section provides us with an answer to our question. As we already mentioned, by default will request the A record. Here, we can see that the domain points to the IP address.
Usually, you do not want to turn off the answer, but you can remove this section from the output using the option.
-
The “AUTHORITY” section tells us what server(s) are the authority for answering DNS queries about the queried domain.
You can disable this section of the output using the option.
-
The “ADDITIONAL” section gives us information about the IP addresses of the authoritative DNS servers shown in the authority section.
The option disables the additional section of a reply.
-
The last section of the output includes statistics about the query.
You can disable this part with the option.
dig command options
Here is the summary of all important options of the dig command on Linux or Unix-like operating systems:
Command line option | Usage |
-x dot-notation | shortcut for reverse lookups |
-i | use IP6.INT for IPv6 reverse lookups |
-f filename | Batch mode |
-b address | Bind to source address/port |
-p port | Specify port number |
-q name | Specify query name |
-t type | Specify query type |
-c class | Specify query class |
-k keyfile | Specify tsig key file |
-y name:key | Specify named base64 tsig key |
-4 | Use IPv4 query transport only |
-6 | Use IPv6 query transport only |
-m | Enable memory usage debugging |
dig command query options
dig command has a number of query options. Each query option is identified by a keyword preceded by a plus sign (+). Some keywords set or reset an option. These may be preceded by the string no to negate the meaning of that keyword. Other keywords assign values to options like the timeout interval. They have the form +keyword=value. The query options are:
Option | Usage |
+vc | TCP mode |
+tcp | TCP mode, alternate syntax |
+time=### | Set query timeout |
+tries=### | Set number of UDP attempts |
+retry=### | Set number of UDP retries |
+domain=### | Set default domainname |
+bufsize=### | Set EDNS0 Max UDP packet size |
+ndots=### | Set NDOTS value |
+edns=### | Set EDNS version |
+search | Set whether to use searchlist |
+showsearch | Search with intermediate results |
+defname | Ditto |
+recurse | Recursive mode |
+ignore | Don’t revert to TCP for TC responses. |
+fail | Don’t try next server on SERVFAIL |
+besteffort | Try to parse even illegal messages |
+aaonly | Set AA flag in query +aaflag |
+adflag | Set AD flag in query |
+cdflag | Set CD flag in query |
+cl | Control display of class in records |
+cmd | Control display of command line |
+comments | Control display of comment lines |
+question | Control display of question |
+answer | Control display of answer |
+authority | Control display of authority |
+additional | Control display of additional |
+stats | Control display of statistics |
+short | Disable everything except shortform of answer |
+ttlid | Control display of ttls in records |
+all | Set or clear all display flags |
+qr | Print question before sending |
+nssearch | Search all authoritative nameservers |
+identify | ID responders in short answers |
+trace | Trace delegation down from root |
+dnssec | Request DNSSEC records |
+nsid | Request Name Server ID |
+multiline | Print records in an expanded format |
+onesoa | AXFR prints only one soa record |
Общие детали
Для начала посмотрим, как выглядит легитимный запрос на zone transfer. Это делается утилитой dig, но сначала поставим tcpdump в режим мониторинга трафика DNS. Чтобы включить TSIG в запросах, нужно указать ключ с помощью опции . Формат такой: .
Снифаем трафик запроса AXFR
Поймалось несколько пакетов, давай посмотрим на них.
Пакет с ответом на AXFR-запрос
На скрине видно TSIG, который сгенерировал сервер на основе нашего ключа. Формат ответа описан в . Согласно спецификации все запросы при общении должны быть подписаны. Сама подпись генерируется на основе следующих компонентов:
- размер MAC (Message authentication code, дайджест) запроса. Под него выделяется два байта;
- MAC-запрос;
- DNS-сообщение ответа;
- ключ TSIG-ответа.
Далее в этой же RFC в указано, что если запрос вызвал ошибку и эта ошибка не имеет отношения непосредственно к TSIG, то в ответ должен улететь пакет с подписью, которая будет сгенерирована в соответствии с указанными выше параметрами.
Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте
Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», увеличит личную накопительную скидку и позволит накапливать профессиональный рейтинг Xakep Score!
Подробнее
Вариант 2. Открой один материал
Заинтересовала статья, но нет возможности стать членом клуба «Xakep.ru»? Тогда этот вариант для тебя!
Обрати внимание: этот способ подходит только для статей, опубликованных более двух месяцев назад.
Я уже участник «Xakep.ru»
Syntax
The basic syntax: Where:
- DNS-server-name – The name or IP address of the name server to query (such as 8.8.8.8 or ns1.cyberciti.biz). If no DNS-server-name is provided, the dig command will use the /etc/resolv.conf file and use name servers listed there.
- Hostname|IPAddress – The name of the resource record that is to be looked up using DNS-server-name.
- type – Set the type of query such as A, MX, NS and more.
List of DNS record types
Before you use the dig command you should aware of common types of resource records of the DNS. Here are most common resource records:
Type | Purpose | Examples |
A | IPv4 IP address | 192.168.1.5 or 75.126.153.206 |
AAAA | IPv6 IP address | 2607:f0d0:1002:51::4 |
CNAME | Canonical name record (Alias) | s0.cyberciti.org is an aliasfor d2m4hyssawyie7.cloudfront.net |
MX | Email server host names | smtp.cyberciti.biz or mx1.nixcraft.com |
NS | Name (DNS) server names | ns1.cyberciti.biz or ns-243.awsdns-30.com |
PTR | Pointer to a canonical name.Mostly used for implementing reverse DNS lookups | 82.236.125.74.in-addr.arpa |
SOA | Authoritative information about a DNS zone | see below |
TXT | Text record | see below |
By default, dig command looks for A records only. Let us see Linux and Unix dig command examples in details.
Sintaxe Dig
De uma forma simples, a sintaxe do dig será como esta:
dig
– o endereço do IP ou hostname do servidor a ser consultado.
Se o argumento do servidor for o hostname, então o dig resolverá o hostname antes de proceder com a consulta ao nome do servidor.
Isto é opcional e se você não fornecer um argumento de servidor, então o dig usará o nome do servidor listado em /etc/resolv.conf.
– o nome do registro de recurso que deve ser pesquisado.
– o tipo de pesquisa solicitada pelo dig. Por exemplo, pode ser um registro A, registro MX, registro SOA ou qualquer outro tipo. Por padrão, o dig executa uma pesquisa por registro A se nenhum tipo de argumento for especificado.
Как указать поределенный DNS сервер в dig
По-умолчанию dig используем DNS сервера указанные в Вашем файле /etc/resolv.conf
Используем параметр @сервер, если хотим указать другой сервер:
$ dig @8.8.8.8 google.com ; <<>> DiG 9.11.3-1ubuntu1.11-Ubuntu <<>> @8.8.8.8 google.com ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 38493 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 0 ;; QUESTION SECTION: ;google.com. IN A ;; ANSWER SECTION: google.com. 58 IN A 172.217.16.142 ;; AUTHORITY SECTION: google.com. 6721 IN NS ns2.google.com. google.com. 6721 IN NS ns3.google.com. google.com. 6721 IN NS ns1.google.com. google.com. 6721 IN NS ns4.google.com. ;; Query time: 7 msec ;; SERVER: 8.8.8.8#53(8.8.8.8) ;; WHEN: Sun Jan 05 14:20:24 +03 2020 ;; MSG SIZE rcvd: 116
Синтаксис
Рассмотрим синтаксис.
dig
Основные параметры:
- -t — какой тип запроса получить, TXT, NS, A;
- -c — какой класс запроса получить, IN;
- -x — преобразование адреса в нормальное написание, обычно опция используется чтобы получить PTR запись;
- A — IP-адрес версии 4;
- AAAA — адрес версии 6;
- CNAME — псевдоним;
- MX — показать Mail eXchange запись;
- NS — имя сервера доменных имен;
- PTR — обратное разрешение;
- SOA — техническая информация о домене;
- TXT -показать txt запись;
- +short -скрывает лишнюю информацию, тем самым выводит только ваш запрос;
- +noall — отключит все секции;
- +noanswer – отключит секцию «ANSWER SECTION»
- +nostats – убирает статистику;
- +nocomments – убирает комментарии;
- +noadditional – убирает «ADDITIONAL SECTION»;
- +noauthority – не покажет на экране «AUTHORITY SECTION».
Примеры
Узнаем айпи адрес сайта. Для этого введем команду без аргументов.
dig vseprolinux.ru
На скриншоте видно секции:
- HEADER -выводит информацию о текущей версии dig;
- QUESTION SECTION — выводит наш запрос. Мы запросили А запись;
- ANSWER SECTION — выводит ответ ДНС сервера.
- ADDITIONAL SECTION — показывает айпи адреса ДНС серверов.
- Область статичтики.
Итого получили:
- A — 195.161.114.71 — это IP-адрес сайта;
- NS — dns сайта;
- 64471 IN A — IP-адрес службы доменных имен;
- Server: 192.168.201.254#53 — айпи адрес текущего ДНС сервера компьютера, который указан в файле /etc/resolv.conf. 53 — это порт.
Получим адрес почтового сервера, так называемые МХ запись. Для этого в качестве аргумента укажем MX.
dig mx vseprolinux.ru
Наша строчка в секции ANSWER SECTION.
Уберем лишнюю информацию, выведем только секцию ANSWER SECTION. Для этого введем дополнительные аргументы +noall +answer.
+noall — отключит все секции, +answer добавит секцию ANSWER SECTION.
dig mx +noal +answer vseprolinux.ru
Узнаем NS запись, без лишней информации.
dig ns +noal +answer vseprolinux.ru
Аналог такой команды можно записать с ключом +short.
dig ns +short vseprolinux.ru
Получим PTR запись. В командной строке пишем аргумент -x и айпи адрес.
dig -x 195.161.114.71
How to Use the Dig Command
Lets get into the basic uses of the command:
Dig a Domain Name
To perform a DNS lookup for a domain name, just pass the name along with the dig command:
dig hostinger.com
By default, the dig command will display the A record when no other options are specified. The output will also contain other information like the installed dig version, technical details about the answers, statistics about the query, a question section along with few other ones.
Short Answers
The above dig command includes a lot of useful information in different sections, but there may be times when you want only the result of the query. You can do that by using the +short option, that will display the IP address (A record) of the domain name only:
dig hostinger.com +short
Detailed Answers
Sometimes you want to view the answers section in details. Therefore, For a detailed information on answers section, you can stop displaying all the section using +noall option and query the answers section only by using +answer option with the dig command.
dig hostinger.com +noall +answer
Specifying Nameservers
By default, dig commands will query the name servers listed in /etc/resolv.conf to perform a DNS lookup for you. You can change this default behavior by using the @ symbol followed by a hostname or IP address of the name server along.
The following dig command sends the DNS query to Google’s name server(8.8.8.8) by using the @8.8.8.8 option.
dig @8.8.8.8 hostinger.com
Query All DNS Record Types
To query all the available DNS record types associated with a domain use the ANY option. The ANY option will include all the available record types in the output:
dig hostinger.com ANY
Search For Record Type
If you want to look up a specific record, just add the type to the end of the command.
dig hostinger.in MX
Similarly, to view the other records associated with a domain, specify the record type at the end of dig command:
dig hostinger.com txt (Query TXT record) dig hostinger.com cname (Query CNAME record) dig hostinger.com ns (Query NS record) dig hostinger.com A (Query A record)
Trace DNS Path
Dig allows tracing the DNS lookup path by using the +trace option. The option makes iterative queries to resolve the name lookup. It will query the name servers starting from the root and subsequently traverses down the namespace tree using iterative queries following referrals along the way:
dig hostinger.com +trace
Reverse DNS Lookup
Reverse DNS lookup lets you look up the domain and hostname associated with an IP address. To perform a reverse DNS lookup using the dig command use the –x option followed by your chosen IP address. In the following example, dig will perform a reverse DNS lookup for the IP address associated with google.com:
dig +answer -x 172.217.166.46
Remember that If a PTR record is not defined for an IP address, then it is not possible to do a reverse DNS lookup since the PTR record points to the domain or hostname.
Batch Queries
With the dig utility, you can perform a DNS lookup for a list of domains instead of doing the same for each one individually. To do that, you need to provide dig with a list of domain names – one per line in a file. Once the file is ready, specify the name of it with -f option:
vi domain_name.txt hostinger.com google.com ubuntu.com
dig -f domain_name.txt +short
Control Dig Behavior
The output of the command can be customized permanently by setting up options in the ~/.digrc file that will run automatically with the command.
Suppose you want to view the answer section only – specify the required options in the ~/.digrc file, so you don’t have to type them in while executing the query.
echo "+noall +answer" > ~/.digrc
Now perform a DNS server lookup for a domain. The output confirms that dig runs with the options set in the ~/.digrc file.
Example Usage
A typical invocation of dig looks like:
dig @server name type
where server is the name or IP address of the name server to query—an IPv4 address in dotted-decimal notation or an IPv6 address in colon-delimited notation. When the supplied server argument is a hostname, dig resolves that name before querying that name server. The reply from the name server that responds is displayed.
The name element specifies the resource record of interest, whereas type indicates what type of query is required—ANY, A, MX, SIG, etc. Type can be any valid query type. If no type argument is supplied, dig will perform a lookup for an A record.
OPTIONS
The -b option sets the source IP address of the query to address. This value must be a valid address on one of the host’s network interfaces.
The default query class (IN for internet) is overridden by the -c option. Class is any valid class, such as HS for Hesiod records or CH for CHAOSNET records.
The -f option makes dig operate in batch mode by reading a list of lookup requests to process from the file filename. The file contains any number of queries, one per line. Each entry in the file should be organised in the same way they would be presented as queries to dig using the command-line interface.
If a non-standard port number is to be queried, use the -p option. Port# is the port number that dig will send its queries instead of the standard DNS port number 53. This option would be used to test a name server that has been configured to listen for queries on a non-standard port number.
The -t option sets the query type to type. It can be any valid query type which is supported in BIND9. The default query type A, unless the -x option is supplied to indicate a reverse lookup.
Reverse lookups—mapping addresses to names—are simplified by the -x option. Addr is an IPv4 address in dotted-decimal notation, or a colon-delimited IPv6 address. When this option is used, there is no need to provide the name, class and type arguments.
To sign the DNS queries sent by dig and their responses using transaction signatures, specify a TSIG key file using the -k option. You can also specify the TSIG key itself on the command line using the -y option; name is the name of the TSIG key and key is the actual key. The key is a base-64 encoded string, typically generated by dnssec-keygen.
DESCRIPTION
dig 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 trou- bleshoot DNS problems because of its flexibility, ease of use and clar- ity of output. Other lookup tools tend to have less functionality than dig. Although dig is normally used with command-line arguments, it also has a batch mode of operation for reading lookup requests from a file. A brief summary of its command-line arguments and options is printed when the -h option is given. Unlike earlier versions, the BIND 9 implementa- tion of dig allows multiple lookups to be issued from the command line. Unless it is told to query a specific name server, dig will try each of the servers listed in /etc/resolv.conf. If no usable server addresses are found, dig will send the query to the local host. When no command line arguments or options are given, dig will perform an NS query for "." (the root). It is possible to set per-user defaults for dig via ${HOME}/.digrc. This file is read and any options in it are applied before the command line arguments. The -r option disables this feature, for scripts that need predictable behaviour. The IN and CH class names overlap with the IN and CH top level domain names. Either use the -t and -c options to specify the type and class, use the -q the specify the domain name, or use "IN." and "CH." when looking up these top level domains.
Sintaxis del comando Dig
En su forma más simple, la sintaxis del comando Dig se verá así:
dig
– la dirección IP o el hostname del nombre del servidor a consultar.
Si el argumento del servidor es el hostname, dig resuelve el hostname antes de continuar con la consulta.
Esto es opcional y si no proporcionas un argumento de servidor, dig utiliza los nombres de servidores que figuran en /etc/resolv.conf.
– el nombre del registro de recursos que se debe buscar.
– el tipo de consulta solicitada por dig. Por ejemplo, puede ser un registro A, un registro MX, un registro SOA o cualquier otro tipo. De forma predeterminada, dig realiza una búsqueda de un registro A si no se especifica ningún argumento de tipo.