- Мониторинг сети в Linux (ping, traceroute, mtr)
- Утилита ping
- Утилита traceroute
- Утилита MTR
- miglen / linux-networking-tools.md
- 15 Linux ping command examples for network diagnostics
- What is the use of the ping command?
- How does ping command work?
- Can I ping with a proxy?
- Ping IPv6 protocol
- Ping a specific port
- Ping with time
- Ping all the hosts on a given subnet
- How to end a ping?
- End after a specific count
Мониторинг сети в Linux (ping, traceroute, mtr)
Существует несколько хороших утилит, позволяющих искать неисправности в сети на уровне TCP/IP. Большинство из них выдает низкоуровневую информацию, поэтому для того чтобы пользоваться ими, нужно хорошо понимать принципы работы протоколов TCP/IP и маршрутизации. В этой статье мы рассмотрим основные инструменты поиска неисправностей в сети: утилитами ping, traceroute и mtr.
Утилита ping
Проверка доступности компьютера
Утилита ping предназначена для того, чтобы при помощи отправки ICMP пакетов убедиться в работоспособности хоста. Команда ping посылает запрос (ICMP ECHO_REQUEST) конкретному компьютеру и фиксирует поступающие ответы (ICMP ECHO_RESPONSE). Её можно применять для работоспособности отдельных компьютеров и сегментов сети. В обработке ее запроса участвуют таблицы маршрутизации, физические компоненты сетей и сетевые шлюзы, поэтому для достижения успешного результата сеть должна быть в более или менее рабочем состоянии. Если команда не работает, можно быть совершенно уверенным в том, что более сложные средства тем более не функционируют. Однако это правило неприменимо в сетях, где брандмауэры блокируют эхо-запросы ICMP. Убедитесь в том, что брандмауэр не препятствует работе команды ping, прежде чем подозревать, что зондируемый компьютер игнорирует эту команду. В конце концов, отключите на короткое время брандмауэр для проверки работоспособности сети.
Если не задан аргумент «число пакетов», команда ping работает в бесконечном цикле. Чтобы прервать работу команды, нужно нажать специальную клавиатурную комбинацию .
Например, пропингуем neoserver.ru (это имя хоста):
Информация о компьютере neoserver.ru включает его IP-адрес, порядковый номер ответного ICMP-пакета и полное время прохождения пакета. Полученные результаты свидетельствуют о том, что компьютер neoserer.ru работает и подключен к сети.
Min — минимальное время ответа хоста, кторому был отправлен запрос.
Avg — среднее время ответа хоста, кторому был отправлен запрос
Max — максимальное время ответа хоста, кторому был отправлен запрос.
Ещё вы увидите TTL — определяет максимальное количество хопов (то есть прыжок, участок между маршрутизаторами), которые пакет может пройти. Наличие этого параметра не позволяет пакету бесконечно ходить по сети.
В ОС Linux, как уже было сказано выше, команда ping без дополнительных параметров будет пинговать заданный хост бесконечно. Чтобы отправить, например, 10 запросов, необходимо добавить ключ -с:
В итоге, мы видим, что было отпралено 10 запросов и выведен результат.
Другие примеры задействования разын ключей:
Не резолвить имена адресов, выводить только ip-адреса
Завершение работы ping по заданному времени (тут 5 секунд)
Установить размер отправляемых пакетов в 1000 байт
Увеличить интервал времени пинга на 3 секунды
Утилита traceroute
Каждый пакет проходит на своем пути определенное количество узлов, пока достигнет своей цели. И, как мы уже знаем, каждый пакет имеет свое время жизни. Это количество узлов, которые может пройти пакет перед тем, как он будет уничтожен. Этот параметр записывается в заголовке TTL, каждый маршрутизатор, через который будет проходить пакет уменьшает его на единицу. При TTL=0 пакет уничтожается, а отправителю отсылается сообщение Time Exceeded.
Команда traceroute linux использует UDP пакеты. Она отправляет пакет с TTL=1 и смотрит адрес ответившего узла, дальше TTL=2, TTL=3 и так пока не достигнет цели. Каждый раз отправляется по три пакета и для каждого из них измеряется время прохождения. Пакет отправляется на случайный порт, который, скорее всего, не занят. Когда утилита traceroute получает сообщение от целевого узла о том, что порт недоступен трассировка считается завершенной.
Синтаксис утилиты не сложный:
Адресом узла может служить как IP адрес, так и доменное имя. Основные опции:
Для примера, выпоним трасировку к ресурсу yandex.ru:
В итоге, пакет прошел через 6 узлов перед тем, как дойти до указанного хоста. На каждый узел отправлялось по три пакета и для каждого из них было засечено время прохождения. И если на одном из узлов возникнет проблема, теперь вы будете знать на каком.
Иногда, вместо одного узла вы можете видеть звездочки. Это значит, что шлюзы либо не высылают нам ICMP с сообщением «time exceeded», либо у их сообщений слишком маленький TTL и оно нас не достигает. В точности нельзя сказать, что происходит на самом деле, но ясно, что по какой-то причине хост не захотел нам отвечать:
Бывает, что трассировка с помощью UDP не работает, это может произойти потому, что фаервол блокирует все лишние пакеты. Можно воспользоваться ICMP с помощью опции -I:
Рассмотреных выше простых примеров, вполне достаточно для первичной диагностики сети как для обычныз пользователей, так и для начинающих администраторов.
Утилита MTR
MTR – это альтернатива программе traceroute. Объединяя функции ping и traceroute, mtr позволяет постоянно опрашивать удаленный сервер и отслеживать изменения задержки и производительности с течением времени.
Синтаксис утилиты также несложный:
Вывод похож на traceroute, но mtr имеет существенное преимущество – ее вывод постоянно обновляется. Это позволяет собирать средние показатели, а также отслеживать тенденции и изменения производительности сети. Как и с утилитой ping, mtr будет работать бесконечно. Чтобы прервать работу команды, нужно нажать специальную клавиатурную комбинацию .
Источник
miglen / linux-networking-tools.md
List of Linux networking tools
Displays contents of /proc/net files. It works with the Linux Network Subsystem, it will tell you what the status of ports are ie. open, closed, waiting, masquerade connections. It will also display various other things. It has many different options. Netstat (Network Statistic) command display connection info, routing table information etc. To displays routing table information use option as -r.
This is a sniffer, a program that captures packets off a network interface and interprets them for you. It understands all basic internet protocols, and can be used to save entire packets for later inspection.
The ping command (named after the sound of an active sonar system) sends echo requests to the host you specify on the command line, and lists the responses received their round trip time. PING (Packet INternet Groper) command is the best way to test connectivity between two nodes. Whether it is Local Area Network (LAN) or Wide Area Network (WAN). Ping use ICMP (Internet Control Message Protocol) to communicate to other devices. You can ping host name of ip address using below command.
traceroute will show the route of a packet. It attempts to list the series of hosts through which your packets travel on their way to a given destination. Also have a look at xtraceroute (one of several graphical equivalents of this program). traceroute is a network troubleshooting utility which shows number of hops taken to reach destination also determine packets traveling path. Below we are tracing route to global DNS server IP Address and able to reach destination also shows path of that packet is traveling.
tracepath performs a very simlar function to traceroute the main difference is that tracepath doesn’t take complicated options.
“ network exploration tool and security scanner”. nmap is a very advanced network tool used to query machines (local or remote) as to whether they are up and what ports are open on these machines.
Dig (domain information groper) query DNS related information like A Record, CNAME, MX Record etc. This command mainly use to troubleshoot DNS related query.
nslookup command also use to find out DNS related query. The following examples shows A Record (IP Address) of tecmint.com.
host command to find name to IP or IP to name in IPv4 or IPv6 and also query DNS records.
hostname is to identify in a network. Execute hostname command to see the hostname of your box. You can set hostname permanently in /etc/sysconfig/network. Need to reboot box once set a proper hostname.
ARP (Address Resolution Protocol) is useful to view / add the contents of the kernel’s ARP tables. To see default table use the command as.
This command is used to configure network interfaces, or to display their current configuration. In addition to activating and deactivating interfaces with the “up” and “down” settings, this command is necessary for setting an interface’s address information if you don’t have the ifcfg script.
- ifup — Use ifup device-name to bring an interface up by following a script (which will contain your default networking settings). Simply type ifup and you will get help on using the script.
- ifdown — Use ifdown device-name to bring an interface down using a script (which will contain your default network settings). Simply type ifdown and you will get help on using the script.
- ifcfg — Use ifcfg to configure a particular interface. Simply type ifcfg to get help on using this script.
The route command is the tool used to display or modify the routing table. To add a gateway as the default you would type:
iwconfig command in Linux is use to configure a wireless network interface. You can see and set the basic Wi-Fi details like SSID channel and encryption. You can refer man page of iwconfig to know more.
Show / manipulate routing, devices, policy routing and tunnels.
- List interfaces with detailed info:
- List interfaces with brief network layer info:
ip -brief address
- List interfaces with brief link layer info:
- Display the routing table:
- Make an interface up/down:
ip link set <
- Add/Delete an ip address to an interface:
ip route add default via <
Источник
15 Linux ping command examples for network diagnostics
Thanks to Linux, we have access to many tools that facilitate networking administration & diagnostics. In this sense, the Linux ping command is one of the most useful tools for sysadmins and network administrators.
Its basic function is to determine if one host of the network is reachable or not. However, in this post, we will address other more advanced capabilities of the Linux Ping command.
Table of Contents
What is the use of the ping command?
The ping command is one of the most basic tools for working with networks. Its purpose is to diagnose network connection errors.
In this way, it is possible to know if a network node has lost connectivity. On the other hand, it is also useful to perform other diagnostic tasks such as the following:
- Measure the time taken by two network nodes to communicate.
- We will also be able to identify the IP address of a specific host. We can use this feature on both the Internet and in a private network.
- The ping command can be used in a bash script to perform automatic checks with network nodes.
- It allows knowing if there is a connection with specific equipment.
As you can see, it is a necessary command for the administration of networks and servers.
How does ping command work?
In Linux, the functioning of the ping command is quite simple to explain. The command sends a series of small packets to a specific node.
You can test this node using either the IP address or the hostname. Then, after you send the packet, the command verifies and measures the time it takes to receive a response from the destination node.
As you may expect, the response time may be affected due to conditions such as the geographical location between the connection points or any piece of the hardware used between the two nodes.
For example, in wired private networks, the command will get better times than with a network with multiple routers or bridges.
However, the information that the command will generate will judge whether the network is in good or bad condition.
The syntax of the command is as follows:
Some of the most useful and used options of the ping command are the following:
- -c: With this option, you can specify how many packets to send.
- -s: This option allows you to change the default size of the packets.
- -v: verbose mode.
- -w: Specifies a time in seconds that the execution of the command will end. No matter how many packets the command has sent or received.
- -i: With this option, you can specify the network interface to use.
The destination node can be specified by an IP address or a hostname.
Can I ping with a proxy?
A proxy is a server or application that acts as an intermediary for the connection between two points on a network. It is the man in the middle who makes the request directly to another node.
The problem is that the Ping command requires a direct network connection between the nodes.
Therefore, the Ping command generally cannot function properly if there is a proxy behind it.
A possible solution is that many websites offer the Ping command service. On the other hand, for some tasks of the ping command, it is possible to use the curl command. Also, you can use a VPN so that it will hide your IP.
However, in some Linux distributions, this command is not installed by default. First, verify it and then install it if it is not installed.
Ping IPv6 protocol
Normally, when using the Ping command, we use IP addresses with the IPv4 protocol. However, with the advent of the IPv6 protocol, it is increasingly common to notice addresses in this format.
The Linux kernel supports the IPv6 protocol since version 2.2, so all Linux distributions currently support it.
The basic syntax is as follows:
On old versions, there was ping6 command. On recent versions of Linux, ping6 doesn’t exist anymore, and its functionality has been merged into ping, and it works the same way as you saw.
The basic syntax is as follows:
With the option -c, we can specify the number of packets to send and with -i for the network interface you will use. For example:
Ping a specific port
Sometimes we want to know if a specific port on a node is active. However, the ping command does not provide this functionality, but it is possible to do it with the telnet command that is installed by default on Linux.
To do this, just use the following syntax:
In this way, it is possible to ping a specific port of a network node in a primitive way.
Ping with time
Although the ping command displays useful information, it may be a little simple. However, it is possible to modify the operation of the command a little, to make it show the date the packet is sent.
This can make the information pleasing to the eye and might be useful for scripts and logs.
This syntax is sufficient to do it. However, you need to install the ccze package.
As you can see, it shows the time for every packet sent.
Ping all the hosts on a given subnet
You can send a ping signal to all hosts on a network or subnet. For this, it is enough to add the option -b and ping the broadcast IP address of any network which ends with 255.
So if the destination is unreachable, maybe they block ICMP packets sent by the ping command, or maybe there is a network problem or a problem on the routing table.
How to end a ping?
By default, the ping command on Linux continuously sends test packets to hosts. However, once the information is available, it becomes necessary to terminate the execution of the ping command.
To do so, simply press the following keys:
This way, the command will immediately stop working.
End after a specific count
You can limit the count of packets to 10 or whatever. When it finishes sending the ten packets, it will stop.
Источник