Сетевые настройки Linux
В этой статье поговорим о настройках сетевого подключения в Linux. Расскажем про команду ifconfig. Посмотрим, как настраивать дистрибутивы Ubuntu, CentOS и прочие).
Перед началом настройки сетевого подключения в Linux нужно сначала проверить, каковы текущие настройки сети. Для этого нам вполне подойдёт команда ifconfig. В принципе, для получения информации мы можем использовать её и без прав ROOT, но если хотим получить привилегии суперпользователя, вводим sudo ifconfig. Результатом выполнения команды станет получение списка имеющихся сетевых подключений и их параметров:
Итак, мы видим, что на нашем компьютере используются два сетевых интерфейса: eth0 и lo. Давайте рассмотрим их подробнее.
Интерфейс lo является локальной петлёй, имеющей IP-адрес 127.0.0.1. Она предназначена для обеспечения сетевого доступа к компьютеру. В принципе, этот интерфейс не требует дополнительных настроек.
Что касается интерфейса eth0, то это не что иное, как Ethernet — сетевая карта, имеющая следующие сетевые параметры: — 192.168.1.18 — это IP-адрес; — 255.255.0.0 — маска сети; — 00:11:5b:91:25:3e — MAC-адрес.
При этом значение RUNNING показывает нам, что в данный момент наш сетевой интерфейс eth0 работает. Кстати, нужно понимать, что в различных версиях Linux имя сетевого интерфейса может быть разным — eth0, eth1, eth2 и т. д.
Если хотим посмотреть тип соединения, скорость и поддерживаемые параметры, набираем:
Вывод будет следующим:
Из него мы видим, что скорость работы сетевого Linux-интерфейса eth0 — 100 Мб/с с Full Duplex (включённым полным дуплексом). Тут можно уточнить, что полный дуплекс отличается от полудуплекса (Half Duplex) тем, что обеспечивает передачу входящих и исходящих данных одновременно, а не поочередно.
Переходим к сетевым настройкам Linux
Узнав информацию о текущих подключениях, можно переходить к настройкам локальной сети в Linux. У нас есть 3 способа сделать это: — через графическую оболочку; — используя команду ifconfig либо инструмент Network Manager; — используя конфигурационные файлы сетевого сервиса Network либо Networking.
В принципе, последний способ считается одним из самых удобных и надёжных. Чтобы настроить сеть в Linux, нужно открыть файл, который содержит конфигурацию интерфейса. Здесь всё будет зависеть от того, какой именно Linux-дистрибутив используется.
Вариант № 1. Сетевые настройки дистрибутивов, основанных на Debian (Ubuntu, Kubuntu и прочие)
Файл с параметрами сетевых подключений здесь:
Чтобы поменять в Linux настройки сети, файл надо открыть с root-правами любым текстовым редактором. Например, используя nano:
Чтобы обеспечить автоматическое получение адресов от DHCP-сервера, нужно прописать:
Если же адрес нужно прописать статически, указываем:
В этой конфигурации мы рассмотрели лишь пример обычной домашней сети, в которой адрес компьютера 192.168.1.2, а адрес DNS-сервера и шлюза (их функции обычно выполняет wifi-роутер) — 192.168.1.1.
Вариант № 2. RedHat-based дистрибутивы (OpenSuse, CentOS, Fedora)
Наш файл с настройками сети Linux находится здесь:
Мы открываем его с помощью nano или vim:
Если нужно обеспечить автоматическое получение настроек от DHCP-сервера:
А вот статический IP-адрес:
В этом случае IP-адреса DNS-серверов прописываются в файле:
Вот, к примеру, для публичных DNS-серверов от Google:
В принципе, это всё, и настройка сети в Linux завершилась. Осталось лишь выполнить перезапуск сети:
Вместо поскриптума
Если нужно выключить и включить сеть в операционной системе Linux, используем всё ту же известную нам команду ifconfig.
Например, следующей командой мы выключим сетевую карту eth0:
А вот команда, включающая сетевую плату в Linux:
Также мы можем полностью остановить работу сетевых интерфейсов:
Теперь включаем всё обратно:
На этом всё. Если хотите получить более профессиональные навыки Linux-администрирования, добро пожаловать на специальный курс в OTUS:
Утилита ip Linux
Если вы начинающий системный администратор, думаю, вам понадобится утилита ip. Она позволяет посмотреть сетевые интерфейсы и IP адреса им присвоенные, посмотреть и настроить таблицу маршрутизации, включать или отключать сетевые интерфейсы, управлять маршрутизацией и ARP, а также многое другое.
Раньше вместо неё использовалось несколько других утилит, одна из них — ipconfig. Однако потом им на замену пришла ip. Сейчас она уже поставляется во всех дистрибутивах, а со временем старые утилиты будут удалены, поэтому разобраться с ней стоит.
Синтаксис и опции утилиты ip
Сначала рассмотрим синтаксис команды. Утилита довольно многофункциональная, поэтому и синтаксис её вызова непростой:
$ ip [опции] объект команда [параметры]
Опции — это глобальные настройки, которые сказываются на работе всей утилиты независимо от других аргументов, их указывать необязательно.
- объект — это тип данных, с которым надо будет работать, например: адреса, устройства, таблица arp, таблица маршрутизации и так далее;
- команды — какое-либо действие с объектом;
- параметры — само собой, командам иногда нужно передавать параметры, они передаются в этом пункте.
Дальше рассмотрим все еще более подробно:
- -v, -Version — только вывод информации об утилите и ее версии.
- -h, -human — выводить данные в удобном для человека виде.
- -s, -stats — включает вывод статистической информации.
- -d, —details — показывать ещё больше подробностей.
- -f, -family — позволяет указать протокол, с которым нужно работать, если протокол не указан, то берется на основе параметров команды. Опция должна принимать одно из значений: bridge, dnet, inet, inet6, ipx или link. По умолчанию используется inet, link — означает отсутствие протокола.
- -o, -oneline — выводить каждую запись с новой строки.
- -r,-resolve — определять имена хостов с помощью DNS.
- -a, -all — применить команду ко всем объектам.
- -c, -color — позволяет настроить цветной, доступные значения: auto, always и never.
- -br, -brief — выводить только базовую информацию для удобства чтения.
- -4 — короткая запись для -f inet.
- -6 — короткая запись для -f inet-f inet6.
- -B — короткая запись для -f inet-f bridge.
- -0 — короткая запись для -f inet -f link.
Теперь давайте рассмотрим самые важные объекты.
- address или a — сетевые адреса.
- link или l — физическое сетевое устройство.
- neighbour или neigh — просмотр и управление ARP.
- route или r — управление маршрутизацией.
- rule или ru — правила маршрутизации.
- tunnel или t — настройка туннелирования.
Конечно, это не все объекты которые поддерживает команда ip Linux, но на первое время вам хватит. Во время ввода имя объекта может быть сокращено до одной буквы. При неоднозначности используется алфавитный порядок. Например, ip a show, расшифровывается как ip address show. Тогда как в ip r show, r — означает route.
Теперь рассмотрим доступные команды, с помощью которых может быть выполнена настройка сети linux. Они зависят от объекта, к которому будут применяться. Вот основные команды: add, change, del или delete, flush, get, list или show, monitor, replace, restore, save, set, и update. Если команда не задана, по умолчанию используется show (показать).
Здесь тоже поддерживается сокращение и в большинстве случаев для выполнения нужного действия достаточно нескольких символов. Но алфавитный порядок соблюдается не всегда. Например, ip a s, означает ip address show, а не ip address set, к сожалению.
Примеры использования ip
Вот теперь мы дошли к самому интересному — примерам использования утилиты ip Linux. То что я здесь опишу на самом деле лишь маленькая капля из всего того что может утилита ip.
1. Просмотр IP адресов
Чтобы посмотреть все IP адреса, связанные с сетевыми интерфейсами используйте такую команду:
Для просмотра информации в кратком виде используйте опцию -br:
Можно посмотреть IP адреса только по определённому сетевому интерфейсу, например: enp0s3:
ip a show enp0s3
ip a show dev enp0s3
Можно отобразить только статические IP адреса:
ip a show dev enp0s3 permanent
Или только динамические:
ip a show dev enp0s3 dynamic
2. Добавление IP адреса
Чтобы присвоить IP адрес для устройства нужно использовать команду add. Её общий синтаксис такой:
$ ip addr add IP_адрес / маска dev интерфейс
Например, давайте присвоим тому же интерфейсу enp0s3 IP адрес 10.0.2.100 с маской подсети 255.255.255.0:
ip addr add 10.0.2.100/255.255.255.0 dev enp0s3
Маску можно указать и в сокращённом виде:
ip addr add 10.0.2.100/24 dev enp0s3
3. Удаление IP адреса
Чтобы удалить IP адрес из интерфейса надо использовать команду del. Синтаксис её очень похож на предыдущую команду. Например, удалим IP адрес 10.0.2.100:
ip addr del 10.0.2.100/255.255.255.0 dev enp0s3
Можно удалять IP адреса по одному или удалить все сразу с помощью команды flush:
Или же можно удалить адреса только определённой подсети:
sudo ip a flush to 10.0.2.0/24
Если вы будете применять эти команды к интерфейсу, с помощью которого у вас работает сеть, то сеть пропадёт и чтобы её вернуть надо будет перезагрузить сетевые службы.
4. Список интерфейсов
Чтобы посмотреть список сетевых интерфейсов используйте объект link:
5. Включение или выключение интерфейсов
Для решения этой задачи тоже используется объект link, но с командой set. Синтаксис её такой:
$ ip link set dev интерфейс действие
В качестве действия можно использовать up или down. Например, чтобы отключить интерфейс enp0s3 выполните:
ip link set dev enp0s3 down
А чтобы включить его обратно:
ip link set dev enp0s3 up
6. Настройка MTU
Параметр MTU означает размер одного пакета, передаваемого по сети. Этот размер можно изменить с помощью команды set. Например, увеличим MTU для enp0s3 до 4000 тысяч байт:
ip link set mtu 4000 dev enp0s3
7. Настройка MAC адреса
Адрес MAC — это физический адрес, который используется для определения какому устройству надо передать сетевой пакет в локальной сети. Прежде чем настраивать MAC адрес ваше устройство надо отключить:
sudo ip link set dev enp0s3 down
Затем можно установить адрес:
sudo ip link set dev enp0s3 address AA:BB:CC:DD:EE:FF
А потом включить интерфейс обратно:
sudo ip link set dev enp0s3 up
8. Таблица ARP
Именно протокол ARP отвечает за преобразование IP адресов в низкоуровневые MAC адреса. Для того чтобы не отправлять ARP запросы каждый раз в сеть, кэш хранится в таблице ARP на протяжении 20-ти минут. Чтобы посмотреть содержимое таблицы ARP используйте такую команду:
9. Добавление записи в таблицу ARP
Обычно записи в эту таблицу попадают автоматически, но вы можете добавить их и вручную. Для этого используйте команду add объекта neigh:
sudo ip neigh add 192.168.0.105 lladdr b0:be:76:43:21:41 dev enp0s3
В этом примере я заставил компьютер думать, что узел с IP 192.168.0.105 это 192.168.0.1. Теперь можно попытаться выполнить ping по этому адресу и оно будет работать, несмотря на то, что реально такого узла в сети нет.
10. Очистка таблицы ARP
Вы можете удалять IP адреса по одному с помощью команды del:
sudo ip neigh del dev enp0s3 192.168.0.105
Можно удалить все записи для определённого сетевого интерфейса:
ip neigh flush dev enp0s3
Или очистить таблицу полностью командой flush:
11. Просмотр таблицы маршрутизации
Для просмотра таблицы маршрутизации используйте объект route и команду show:
12. Добавление маршрута
Синтаксис добавления нового маршрута в таблицу маршрутизации такой:
$ ip route add подсеть / маска via шлюз
Вместо шлюза можно указать сетевой интерфейс с помощью которого надо отправлять пакеты:
$ ip route add подсеть / маска dev устройство
Например, добавим новый маршрут для сети через тот же IP адрес:
sudo ip route add 169.255.0.0 via 169.254.19.153
Или можно указать сетевой интерфейс через который надо отправлять пакеты для определённой сети:
sudo ip route add 169.255.0.0 dev enp0s3
13. Удаление маршрута
Удалить маршрут можно командой с аналогичным синтаксисом, только вместо add надо использовать del:
sudo ip route del 169.255.0.0 via 169.254.19.153
Выводы
Вот и подошла к завершению наша статья. Надеюсь, утилита ip Linux уже не кажется такой непонятной. Если у вас есть вопросы или хотите предложить ещё какие-нибудь примеры, пишите комментарии!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7d99ce73db172d43 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
22 Linux Networking Commands for Sysadmin
A system administrator’s routine tasks include configuring, maintaining, troubleshooting, and managing servers and networks within data centers. There are numerous tools and utilities in Linux designed for administrative purposes.
In this article, we will review some of the most used command-line tools and utilities for network management in Linux, under different categories. We will explain some common usage examples, which will make network management much easier in Linux.
On this page
This list is equally useful to full-time Linux network engineers.
Network Configuration, Troubleshooting, and Debugging Tools
1. ifconfig Command
ifconfig is a command-line interface tool for network interface configuration and is also used to initialize interfaces at system boot time. Once a server is up and running, it can be used to assign an IP Address to an interface and enable or disable the interface on demand.
It is also used to view the IP Address, Hardware / MAC address, as well as MTU (Maximum Transmission Unit) size of the currently active interfaces. ifconfig is thus useful for debugging or performing system tuning.
Here is an example to display the status of all active network interfaces.
To list all interfaces which are currently available, whether up or down, use the -a flag.
To assign an IP address to an interface, use the following command.
To activate a network interface, type.
To deactivate or shut down a network interface, type.
Note: Although ifconfig is a great tool, it is now obsolete (deprecated), its replacement is the ip command which is explained below.
2. IP Command
ip command is another useful command-line utility for displaying and manipulating routing, network devices, interfaces. It is a replacement for ifconfig and many other networking commands. (Read our article “What’s Difference Between ifconfig and ip Command” to learn more about it.)
The following command will show the IP address and other information about a network interface.
To temporarily assign IP Address to a specific network interface (eth0), type.
To remove an assigned IP address from a network interface (eth0), type.
To show the current neighbor table in the kernel, type.
3. ifup, ifdown, and ifquery command
ifup command actives a network interface, making it available to transfer and receive data.
ifdown command disables a network interface, keeping it in a state where it cannot transfer or receive data.
ifquery command used to parse the network interface configuration, enabling you to receive answers to query about how it is currently configured.
4. Ethtool Command
ethtool is a command-line utility for querying and modifying network interface controller parameters and device drivers. The example below shows the usage of ethtool and a command to view the parameters for the network interface.
5. Ping Command
ping (Packet INternet Groper) is a utility normally used for testing connectivity between two systems on a network (Local Area Network (LAN) or Wide Area Network (WAN)). It uses ICMP (Internet Control Message Protocol) to communicate to nodes on a network.
To test connectivity to another node, simply provide its IP or hostname, for example.
You can also tell ping to exit after a specified number of ECHO_REQUEST packets, using the -c flag as shown.
6. Traceroute Command
Traceroute is a command-line utility for tracing the full path from your local system to another network system. It prints a number of hops (router IPs) in that path you travel to reach the end server. It is an easy-to-use network troubleshooting utility after the ping command.
In this example, we are tracing the route packets take from the local system to one of Google’s servers with IP address 216.58.204.46.
7. MTR Network Diagnostic Tool
MTR is a modern command-line network diagnostic tool that combines the functionality of ping and traceroute into a single diagnostic tool. Its output is updated in real-time, by default until you exit the program by pressing q .
The easiest way of running mtr is to provide it a hostname or IP address as an argument, as follows.
Sample Output
You can limit the number of pings to a specific value and exit mtr after those pings, using the -c flag as shown.
8. Route Command
The route is a command-line utility for displaying or manipulating the IP routing table of a Linux system. It is mainly used to configure static routes to specific hosts or networks via an interface.
You can view the Kernel IP routing table by typing.
There are numerous commands you can use to configure routing. Here are some useful ones:
Add a default gateway to the routing table.
Add a network route to the routing table.
Delete a specific route entry from the routing table.
9. Nmcli Command
Nmcli is an easy-to-use, scriptable command-line tool to report network status, manage network connections, and control the NetworkManager.
To view all your network devices, type.
To check network connections on your system, type.
To see only the active connections, add the -a flag.
Network Scanning and Performance Analysis Tools
10. Netstat Command
netstat is a command-line tool that displays useful information such as network connections, routing tables, interface statistics, and much more, concerning the Linux networking subsystem. It is useful for network troubleshooting and performance analysis.
Additionally, it is also a fundamental network service debugging tool used to check which programs are listening on what ports. For instance, the following command will show all TCP ports in listening mode and what programs are listening on them.
To view the kernel routing table, use the -r flag (which is equivalent to running the route command above).
Note: Although Netstat is a great tool, it is now obsolete (deprecated), its replacement is the ss command which is explained below.
11. ss Command
ss (socket statistics) is a powerful command-line utility to investigate sockets. It dumps socket statistics and displays information similar to netstat. In addition, it shows more TCP and state information compared to other similar utilities.
The following example shows how to list all TCP ports (sockets) that are open on a server.
To display all active TCP connections together with their timers, run the following command.
12. NC Command
NC (NetCat) also referred to as the “Network Swiss Army knife”, is a powerful utility used for almost any task related to TCP, UDP, or UNIX-domain sockets. It is used to open TCP connections, listen on arbitrary TCP and UDP ports, perform port scanning plus more.
You can also use it as a simple TCP proxy, for network daemon testing, to check if remote ports are reachable, and much more. Furthermore, you can employ nc together with pv command to transfer files between two computers.
The following example will show how to scan a list of ports.
You can also specify a range of ports as shown.
The following example shows how to use nc to open a TCP connection to port 5000 on server2.tecmint.lan, using port 3000 as the source port, with a timeout of 10 seconds.
13. Nmap Command
Nmap (Network Mapper) is a powerful and extremely versatile tool for Linux system/network administrators. It is used to gather information about a single host or explores networks an entire network. Nmap is also used to perform security scans, network audits and finding open ports on remote hosts and so much more.
You can scan a host using its hostname or IP address, for instance.
Alternatively, use an IP address as shown.
Read our following useful articles on the nmap command.
DNS Lookup Utilities
14. host Command
host command is a simple utility for carrying out DNS lookups, it translates hostnames to IP addresses and vice versa.
15. dig Command
dig (domain information groper) is also another simple DNS lookup utility, that is used to query DNS related information such as A Record, CNAME, MX Record etc, for example:
16. NSLookup Command
Nslookup is also a popular command-line utility to query DNS servers both interactively and non-interactively. It is used to query DNS resource records (RR). You can find out the “A” record (IP address) of a domain as shown.
You can also perform a reverse domain lookup as shown.
Linux Network Packet Analyzers
17. Tcpdump Command
Tcpdump is a very powerful and widely used command-line network sniffer. It is used to capture and analyze TCP/IP packets transmitted or received over a network on a specific interface.
To capture packets from a given interface, specify it using the -i option.
To capture a specific number of packets, use the -c option to enter the desired number.
You can also capture and save packets to a file for later analysis, use the -w flag to specify the output file.
18. Wireshark Utility
Wireshark is a popular, powerful, versatile, and easy-to-use tool for capturing and analyzing packets in a packet-switched network, in real-time.
You can also save data it has captured to a file for later inspection. It is used by system administrators and network engineers to monitor and inspect the packets for security and troubleshooting purposes.
19. Bmon Tool
bmon is a powerful, command line-based network monitoring and debugging utility for Unix-like systems, it captures networking-related statistics and prints them visually in a human-friendly format. It is a reliable and effective real-time bandwidth monitor and rate estimator.
Linux Firewall Management Tools
20. Iptables Firewall
iptables is a command-line tool for configuring, maintaining, and inspecting the tables IP packet filtering and NAT ruleset. It is used to set up and manage the Linux firewall (Netfilter). It allows you to list existing packet filter rules; add or delete or modify packet filter rules; list per-rule counters of the packet filter rules.
You can learn how to use Iptables for various purposes from our simple yet comprehensive guides.
21. Firewalld
Firewalld is a powerful and dynamic daemon to manage the Linux firewall (Netfilter), just like iptables. It uses “networks zones” instead of INPUT, OUTPUT, and FORWARD CHAINS in iptables. On current Linux distributions such as RHEL/CentOS 7 and Fedora 21+, iptables is actively being replaced by firewalld.
To get started with firewalld, consult these guides listed below:
Important: Iptables is still supported and can be installed with the YUM package manager. However, you can’t use Firewalld and iptables at the same time on the same server – you must choose one.
22. UFW (Uncomplicated Firewall)
UFW is a well-known and default firewall configuration tool on Debian and Ubuntu Linux distributions. It is used to enable/disable system firewall, add/delete/modify/reset packet filtering rules, and much more.
To check UFW firewall status, type.
If the UFW firewall is not active, you can activate or enable it using the following command.
To disable the UFW firewall, use the following command.
If you want to find more information about a particular program, you can consult its man pages as shown.
That’s all for now! In this comprehensive guide, we reviewed some of the most used command-line tools and utilities for network management in Linux, under different categories, for system administrators, and equally useful to full-time network administrators/engineers.
You can share your thoughts about this guide via the comment form below. If we have missed any frequently used and important Linux networking tools/utilities or any useful related information, also let us know.