- 60 Linux Networking commands and scripts
- Linux Networking commands and scripts
- Tags: scripts, sysadmins
- Download my free 101 Useful Linux Commands (PDF).
- Лучшие сетевые утилиты Linux
- Лучшие сетевые утилиты Linux
- Выводы
- 14 Useful Linux Networking Commands
- ip link
- ip address
- ip route
- iPerf
- traceroute
- tcpdump
- netstat
- scp and sftp
- Ifconfig
- telnet
- nslookup
- Summary
60 Linux Networking commands and scripts
Recently, I wanted to test network throughput via command line with at least 3 tools. For the life of me, I could not remember iperf. Not being able to remember previously used command line tools is frustrating and something we can all relate to. So I created a go-to-list of network tools for myself. Then, I thought, why not turn this list into a blog post? So I spent another hour or two compiling this ongoing list of Linux Networking Commands and Scripts. I look forward mostly to suggestions, because I know there’s always something missing or new scripts out there to try.
Linux Networking commands and scripts
This list of Linux Networking commands and scripts will receive ongoing updates, similar to the other lists on this blog…
- aria2 – downloading just about everything. Torrents included.
- arpwatch – Ethernet Activity Monitor.
- bmon – bandwidth monitor and rate estimator.
- bwm-ng – live network bandwidth monitor.
- curl – transferring data with URLs. (or try httpie)
- darkstat – captures network traffic, usage statistics.
- dhclient – Dynamic Host Configuration Protocol Client
- dig – query DNS servers for information.
- dstat – replacement for vmstat, iostat, mpstat, netstat and ifstat.
- ethtool – utility for controlling network drivers and hardware.
- gated – gateway routing daemon.
- host – DNS lookup utility.
- hping – TCP/IP packet assembler/analyzer.
- ibmonitor – shows bandwidth and total data transferred.
- ifstat – report network interfaces bandwidth.
- iftop – display bandwidth usage.
- ip (PDF file) – a command with more features that ifconfig (net-tools).
- iperf3 – network bandwidth measurement tool. (above screenshot Stacklinux VPS)
- iproute2 – collection of utilities for controlling TCP/IP.
- iptables – take control of network traffic.
- IPTraf – An IP Network Monitor.
- iputils – set of small useful utilities for Linux networking.
- iw – a new nl80211 based CLI configuration utility for wireless devices.
- jwhois (whois) – client for the whois service.
- “lsof -i” – reveal information about your network sockets.
- mtr – network diagnostic tool.
- net-tools – utilities include: arp, hostname, ifconfig, netstat, rarp, route, plipconfig, slattach, mii-tool, iptunnel and ipmaddr.
- ncat – improved re-implementation of the venerable netcat.
- netcat – networking utility for reading/writing network connections.
- nethogs – a small ‘net top’ tool.
- Netperf – Network bandwidth Testing.
- netplan – Netplan is a utility for easily configuring networking on a linux system.
- netsniff-ng – Swiss army knife for daily Linux network plumbing.
- netwatch – monitoring Network Connections.
- ngrep – grep applied to the network layer.
- nload – display network usage.
- nmap – network discovery and security auditing.
- nmcli – a command-line tool for controlling NetworkManager and reporting network status.
- nmtui – provides a text interface to configure networking by controlling NetworkManager .
- nslookup – query Internet name servers interactively.
- ping – send icmp echo_request to network hosts.
- route – show / manipulate the IP routing table.
- slurm – network load monitor.
- snort – Network Intrusion Detection and Prevention System.
- smokeping – keeps track of your network latency.
- socat – establishes two bidirectional byte streams and transfers data between them.
- speedometer – Measure and display the rate of data across a network.
- speedtest-cli – test internet bandwidth using speedtest.net
- ss – utility to investigate sockets.
- ssh – secure system administration and file transfers over insecure networks.
- tcpdump – command-line packet analyzer.
- tcptrack – Displays information about tcp connections on a network interface.
- telnet – user interface to the TELNET protocol.
- tracepath – very similar function to traceroute.
- traceroute – print the route packets trace to network host.
- vnStat – network traffic monitor.
- websocat – Connection forwarder from/to web sockets to/from usual sockets, in style of socat.
- wget – retrieving files using HTTP, HTTPS, FTP and FTPS.
- Wireless Tools for Linux – includes iwconfig, iwlist, iwspy, iwpriv and ifrename.
- Wireshark – network protocol analyzer.
Tags: scripts, sysadmins
Download my free 101 Useful Linux Commands (PDF).
Also, I’ll notify you when new Linux articles are published. — Subscribe now and receive my free PDF.
(Average of 1 or 2 emails per month, sent only on Mondays.)
Источник
Лучшие сетевые утилиты Linux
Очень часто на серверах или обычных компьютерах с операционной системой Linux приходится настраивать сеть. Пользователям домашнего компьютера вряд ли понадобятся все эти утилиты. Но вот для администраторов серверов или даже сетей, это вещь незаменимая. Особенно когда нужно понять почему не работает сеть или выяснить на каком сетевом узле прерывается передача пакетов.
В этой статье мы рассмотрим полезные сетевые утилиты Linux, это самые основные команды, которые можно использовать для администрирования сети в Linux. Эта статья не научит вас всем тонкостями использования таких команд, это всего лишь небольшой список с кратким описанием.
Лучшие сетевые утилиты Linux
ping хост — позволяет отправить ICMP запрос на удалённый хост. Пакеты будут отправляется непрерывно, пока вы не нажмете Ctrl+C. Когда пакет будет отправлен, хост должен отправить ответное ICMP сообщение, это и будет означать, что другой хост работает. Подробнее про ping читайте тут.
telnet хост порт — позволяет проверить доступность определенного порта на хосте. По умолчанию telnet использует порт 23, но также можно использовать и другие. Нажмите Ctrl+] чтобы завершить работу telnet. Подробнее читайте в статье команда telnet linux.
arp — протокол ARP используется для преобразования IP адресов интернет в физические адреса используемой сети. Эта команда, если передать ей опцию -a позволяет вывести таблицу маршрутизации на вашем устройстве. С помощью опции -d можно удалить все записи. Так или иначе все записи удаляются по истечении 20 минут после добавления.
route — с помощью маршрутизации операционная система определяет к какому узлу надо передать тот или иной пакет. Без параметров эта утилита выводит текущую таблицу маршрутизации. Параметр flush позволяет удалить все маршруты, а add добавить новый маршрут. Подробнее читайте тут.
traceroute ip_адрес — очень полезная утилита, для отслеживания маршрута пакетов. Чаще всего с помощью этой команды выполняется проверка сети linux. Пакет отправляет сообщение на компьютер-отправитель со всех шлюзов между источником и пунктом назначения. Подробнее в статье Команда traceroute.
nslookup домен — отправить запрос DNS серверу, на преобразование доменного имени в IP. Например, nslookup ya.ru вернет IP адрес сервера ya.ru. Подробнее тут.
ip — популярная современная утилита для просмотра сетевых подключений в системе Linux. Позволяет посмотреть сетевые интерфейсы, IP адреса, маску сети, таблицу маршрутизации и многое другое. Подробнее в статье Команда ip в Linux.
iw — позволяет управлять беспроводными интерфейсами, просматривать список подключённых или доступных беспроводных сетей.
ifconfig интерфейс — устаревший аналог утилиты ip. Позволяет посмотреть информацию о сетевых подключениях, IP адрес, маску сети и другие параметры. Без параметров выводит список всех интерфейсов в системе, в параметрах можно передать конкретный интерфейс, по которому надо получить данные. Кроме того, можно поднимать или отключать сетевые интерфейсы. Подробнее тут.
tcpdump — консольный сетевой анализатор, позволяющий посмотреть трафик, проходящий через сетевой интерфейс. Можно анализировать содержимое сетевых пакетов и их тип. Подробнее читайте здесь.
ethtool — позволяет смотреть и изменять параметры сетевой карты.
ss — позволяет вывести все открытые локальные сокеты и проанализировать какие программы их используют. Можно отдельно выводить UDP, TCP и Unix сокеты, а также смотреть к каким удалённым сокетам подключены программы компьютера. Подробнее тут.
netstat — устаревший аналог ss, вместо подсистемы ядра здесь используется файловая система proc, а также данные выводятся немного в другом формате.
nc — утилита позволяет создавать новые сетевые сокеты и подключаться к существующим по сети. Это может понадобиться для тестирования работы сети или приложений. Подробнее тут.
iperf — программа позволяет проверить скорость и стабильность сетевого подключения.
iptraf — позволяет смотреть статистику о сетевых подключениях в реальном времени. С помощью этой утилиты вы можете оценить с какой скоростью передаются данные на ваших сетевых интерфейсах.
Выводы
В этой статье мы рассмотрели самые полезные сетевые утилиты Linux, с помощью них вы можете выполнять тестирование сети, проверить сеть на работоспособность и обнаружить неполадки. Более подробную информацию по каждой из них вы можете найти в официальной документации или в отдельных статьях на сайте.
Источник
14 Useful Linux Networking Commands
Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Configuring, monitoring, and securing networks form an essential part of a Sysadmin’s job. When it comes to managing Linux networks, there are many commands and utilities available.
At times networked systems fail. You as an administrator are required to diagnose and resolve issues. Monitoring helps in detecting problems and fixing them before things get out of hand. Monitoring for security and performance also forms an essential part of an admin’s activities.
Here we discuss some commonly used commands to manage Linux networks.
The iproute2 package includes the IP command which is used for network and routing configuration. This replaces the traditional ifconfig and route commands.
ip takes a second argument that specifies the object on which you wish to execute a command and an action like add, delete, or show.
ip link
ip link is for configuring, adding, and deleting network interfaces. Use ip link show command to display all network interfaces on the system :
You can see the man page for ip link with:
ip address
Use ip address command to display addresses, bind new address or delete old ones. The man page ip address command is named as ip-address.
For example, the following command shows the IP address assigned to the network interface enp0s8:
ip route
Use the IP route to print or display the routing table. The following command displays the contents of the routing table:
While Nmap had been used in many movies, The Matrix Reloaded ( Wikipedia , IMDB , Amazon ) turned Nmap into a movie star!.
Nmap (“Network Mapper”) is a powerful utility used for network discovery, security auditing, and administration. Many system admins use it to determine which of their systems are online, and also for OS detection and service detection.
The default Nmap scan shows the ports, their state (open/closed), and protocols. It sends a packet to 1000 most common ports and checks for the response.
To check which hosts on your network are up:
Use -O flag to identify which operating system a host is running.
A word of caution: Nobody appreciates their systems being scanned over the internet. So before you do so, seek permission.
You can also use Nmap on Windows, check out this installation guide.
Use ping to see if a host is alive. This super simple command helps you check the status of a host or a network segment. Ping command sends an ICMP ECHO_REQUEST packet to the target host and waits to see if it replies.
However, some hosts block ICMP echo requests with a firewall. Some sites on the internet may also do the same.
By default, ping runs in an infinite loop. To send a defined number of packets, use -c flag.
With -o flag ping exits successfully after receiving one reply packet.
You can use -n flag to avoid reverse DNS lookups. The ICMP sequence number is particularly important. A Break in sequence numbers indicates lost packets.
A failed ping could be due to
- network failure
- host being not alive
- firewall blocking ICMP ECHO requests
You can also perform an online ping test to check the connectivity from different parts of the world.
iPerf
While ping verifies the availability of a host, iPerf helps analyze and measure network performance between two hosts. With iPerf, you open a connection between two hosts and send some data. iPerf then shows the bandwidth available between the two hosts.
You can install an iPerf using your distribution package manager. For example on Ubuntu-based distributions you can install like this:
Once you have installed iPerf on both the machines, start the iPerf server on one of them. The following example starts the iPerf server on a host with IP address 10.0.0.51.
On the second machine start iPerf with the -c flag. This connects with the server and sends some data.
iPerf returns with the bandwidth results in a few seconds.
traceroute
If ping shows missing packets, you should use traceroute to see what route the packets are taking. Traceroute shows the sequence of gateways through which the packets travel to reach their destination. For example, traceroute from my machine to google.com shows the following:
Line 4 in this output shows a * in the round trip times. This indicates no response was received. This can be due to many reasons – as the traceroute ICMP packets are low-priority, these may be dropped by a router. Or there could be simply congestion. If you see a * in all the time fields for a given gateway, then possibly the gateway is down.
Many web-based route tracing tools allow you to do a reverse traceroute, that is, from a website to your host. You can check these at traceroute.org or Geekflare Traceroute.
tcpdump
tcpdump is a packet sniffing tool and can be of great help when resolving network issues. It listens to the network traffic and prints packet information based on the criteria you define.
For example, you can examine all packets sent to or from a particular host, Ubuntu18 in this example:
By default, tcpdump resolves IP addresses to hostnames. Use -n flag, if you do not want tcpdump to perform name lookups.
tcpdump output prints one line for each packet. Use -c flag to limit output, 5 in the example above.
tcpdump is useful for solving network problems and also identifying potential problems. It is a good idea to run a tcpdump on your network occasionally to verify everything is in order.
netstat
Netstat command is used to examine network connections, routing tables, and various network settings and statistics.
Use -i flag to list the network interfaces on your system.
Here is an example:
Using -r flag will display the routing table. This shows the path configured for sending network packets.
An asterisk in the last two lines indicates that no gateway is required to send packets to any host on these networks. This host is directly connected to the networks 10.0.0.0 and 10.0.2.0.
In the first line, the destination is the default, which means any packet destined for a network not listed in this table is handled by the router 10.0.2,2.
netstat command without any options displays a list of open sockets. Use -l flag to show only listening sockets, which by default, are not shown. You can use -a flag to show listening and non-listening sockets. Here is an example:
More Netstat command example here
Linux installations have a lot of services running by default. These should be disabled or preferably removed, as this helps in reducing the attack surface. You can see what services are running with the netstat command. While netstat is still available, most Linux distributions are transitioning to ss command.
use ss command with -t and -a flags to list all TCP sockets. This displays both listening and non-listening sockets.
To display only TCP connections with state established:
ssh enables you to connect securely with remote hosts over the internet. Earlier rlogin and telnet were used to connect to and administer remote hosts. However, both suffer from a fundamental flaw, that is, they send all information including login names and passwords in cleartext.
ssh enables secure communication over the internet with the following two features :
- It confirms that the remote host is, who it says it is.
- It encrypts all communication between the hosts.
To connect to a remote host you need to have an OpenSSH server running on the remote host. You can install it using your distribution package manager. For example on Ubuntu you can install it like this:
Here is an example showing how you can connect to the remote host 10.0.0.50 using the ssh command:
You get a message saying that the authenticity of the host 10.0.0.50 cannot be established, this is because it’s the first time a connection is being made with 10.0.0.50 (server) and the ssh client has never seen this remote host before. Enter yes to continue connecting. Once the connection has been established, you are prompted for a password:
After you enter the correct password, you are logged into the remote host.
You can exit this remote shell with the exit command.
Also, you can easily execute a single command on the remote host using ssh. For example, to run df -h on the remote host:
scp and sftp
scp (secure copy) is very similar to cp command for copying files, with an addition – you can include remote hostnames in the source or destination pathnames. The hostname and the directory path are separated by a colon. This enables you to copy files securely over the network in an encrypted form. The following command copies a.txt from the local machine to 10.0.0.50 :
sftp (secure ftp) is also a file copy program similar to ftp . However, it uses an SSH encrypted tunnel to copy files, instead of sending everything in cleartext. Also, you do not need an FTP server running on the remote host. You only need an ssh server. Here is an example session:
Ifconfig
Mostly we use ifconfig command to check the IP address assigned to the system.
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 servers.
telnet
telnet connect destination’s host and port via a telnet protocol if a connection establishes means connectivity between two hosts is working fine.
nslookup
nslookup is a program to query domain name servers and resolving IP.
Summary
Networking in Linux is a vast subject, with a large number of commands and utilities. In this article, we have discussed some commonly used commands which hopefully, will help you in managing and securing your network.
Источник