- Настройка сети с помощью утилиты ip в Debian linux
- Синтаксис
- Понимание синтаксиса OBJECTS в комманде ip
- Примеры использования команды ip
- Показать информацию обо всех сетевых интерфейсах
- Назначить интерфейсу IP адрес
- Добавить широковещательный адрес на интерфейс
- Удалить IP адрес с интерфейса
- Сбросить ряд IP адресов с интерфейса
- Как изменить состояние интерфейса на UP или DOWN
- Как изменить txqueuelen устройства
- Как изменить MTU устройства
- Показать соседей (arp кэш)
- Добавить новую ARP запись
- Удалить ARP запись
- Очистить ARP запись
- ip route: команды управления таблицей маршрутизации
- Показать таблицу маршрутизации
- Добавить новый маршрут
- Удалить маршрут
- How to Set Static IP Address and Configure Network in Linux
- Configure Static IP Address in RHEL/CentOS/Fedora:
- Set Static IP Address in Debian / Ubuntu
- Conclusion:
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- 10 Useful “IP” Commands to Configure Network Interfaces
- How Do I Configure Static IP Address Internet Protocol (IPv4)
- For RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux
- For Ubuntu/Debian/Linux Mint
- 1. How to Assign an IP Address to a Specific Interface
- 2. How to Check an IP Address
- 3. How to Remove an IP Address
- 4. How to Enable Network Interface
- 5. How to Disable Network Interface
- 6. How do I Check Route Table?
- 7. How do I Add Static Route
- 8. How to Remove Static Route
- 9. How do I Add Persistence Static Routes
- For RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux
- For Ubuntu/Debian/Linux Mint
- 10. How do I Add Default Gateway
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Настройка сети с помощью утилиты ip в Debian linux
Команда ip используется для назначения адреса сетевому интерфейсу и/или конфигурирования параметров сетевого интерфейса в дистрибутивах Linux. Эта команда заменяет собой старую добрую и ныне устаревшую команду ifconfig в современных дистрибутивах Linux.
Команда ip может использоваться для следующих целей:
- Узнать какие интерфейсы сконфигурированы в системе.
- Запросить статус IP интерфейса.
- Сконфигурировать локальный, Ethernet и другие интерфейсы.
- Пометить интефейс как up или down.
- Сконфигурировать или изменить статическую маршрутизацию или маршрутизацию по умолчанию.
- Сконфигурировать туннель через IP.
- Сконфигурировать содержимое ARP или NDISC кэша.
- Назначить IP адресы, маршруты, подсети и другую IP информацию на интерфейс.
Синтаксис
Понимание синтаксиса OBJECTS в комманде ip
OBJECTS может быть одним из следующих и может записываться в полной или сокращенной форме:
Объект | Сокращенная форма | Задача |
---|---|---|
link | l | Сетевое устройство. |
address | a, addr | IP адрес на устройстве. |
addrlabel | addrl | Управление метками для выбора адреса. |
neighbour | n, neigh | Записи для ARP или NDISC кэшей. |
route | r | Управление записямя таблицы маршрутизации. |
rule | ru | Правила в базе политик маршрутизации. |
maddress | m, maddr | Мультикаст адрес. |
mroute | mr | Записи мультикастового кэша маршрутизации. |
tunnel | t | Туннель через IP. |
xfrm | x | Фреймворк для протокола IPsec. |
Чтобы получить информацию о каждом из объектов используйте команду help следующим образом:
Предупреждение : команды описанные ниже должны выполняться с осторожностью, так как ошибка может привести к потере соединения с сервером. Вы должны быть особо аккуратны при работе в удаленной сессии по ssh.
Примеры использования команды ip
Не пугайтесь синтаксиса команды ip. Давайте сразу начнем с примеров.
Показать информацию обо всех сетевых интерфейсах
Введите следующую команду чтобы получить список всех ip адресов назначенных всем сетевым интерфейсам:
1: lo: mtu 65536 qdisc noqueue state UNKNOWN group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0:
mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:8b:46:9a brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe8b:469a/64 scope link
valid_lft forever preferred_lft forever
Вы можете выбрать между IPv4 и IPv6 используя следующий синтаксис:
Также существует возможность вывести детали только об определенном сетевом интерфейсе:
Назначить интерфейсу IP адрес
Для того чтобы добавить IP адрес используется синтаксис следующего вида:
Чтобы назначить адрес 192.168.1.200/255.255.255.0 на интерфейс eth0, введите:
Добавить широковещательный адрес на интерфейс
По умолчанию, команда ip не задает какой-либо широковещательный адрес до тех пор, пока это будет недвусмысленно указано. Таким образом следующий синтаксис задает широковещательный адрес ADDRESS:
Существует возможность использовать специальные символы + и — вместо широковещательного адреса указывая хостовую часть адреса. В этом примере добавим адрес 192.168.1.50 с маской 255.255.255.0 (/24) со стандартным широковещательным адресом и зададим название eth0Work на интерфейс eth0:
Вы можете задать лупбек адрес на лупбек интерфейсе lo следующим образом:
Удалить IP адрес с интерфейса
Синтаксис для удаления IPv4/IPv6 адреса следующий:
Чтобы удалить 192.168.1.200/24 с интерфейса eth0, введите:
Сбросить ряд IP адресов с интерфейса
Вы можете удалять IP адреса с интерфейса по одному, как показано выше. Однако команда flush может удалить набор адресов с интерфейса по указанному признаку. Например, вы можете удалить все адреса из частной сети 192.168.2.0/24 с помощью команды:
2: eth0 inet 192.168.2.201/24 scope global secondary eth0
2: eth0 inet 192.168.2.200/24 scope global eth0
*** Round 1, deleting 2 addresses ***
*** Flush is complete after 1 round ***
Вы можете выключить IP адрес на всех ppp (Point-to-Point) интерфейсах:
Еще один пример для всех Ethernet интерфейсов:
Как изменить состояние интерфейса на UP или DOWN
К примеру, чтобы положить интерфейс eth1, используйте:
А чтобы поднять этот же интерфейс:
Как изменить txqueuelen устройства
Вы можете установить длину очереди передачи устройства с помощью ifconfig или команды ip следующим образом:
В этом примере изменим txqueuelen со значения по умолчанию, равного 1000, на 10000 для интерфейса 10000:
Как изменить MTU устройства
Для гигабиных сетей вы можете установить максимальный размер блоков передачи (MTU) для лучшей производительности сети. Синтаксис следующий:
Например, установим MTU устройства eth0 на 9000:
2: eth0: mtu 9000 qdisc pfifo_fast state UP qlen 1000
link/ether 00:08:9b:c4:30:30 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.10/24 brd 192.168.1.255 scope global eth1
inet6 fe80::208:9bff:fec4:3030/64 scope link
valid_lft forever preferred_lft forever
Показать соседей (arp кэш)
Пример вывода (часть информации скрыта):
74.xx.yy.zz dev eth1 lladdr 00:30:48:yy:zz:ww REACHABLE
10.10.29.66 dev eth0 lladdr 00:30:48:c6:0a:d8 REACHABLE
74.ww.yyy.xxx dev eth1 lladdr 00:1a:30:yy:zz:ww REACHABLE
10.10.29.68 dev eth0 lladdr 00:30:48:33:bc:32 REACHABLE
74.fff.uu.cc dev eth1 lladdr 00:30:48:yy:zz:ww STALE
74.rr.ww.fff dev eth1 lladdr 00:30:48:yy:zz:ww DELAY
10.10.29.65 dev eth0 lladdr 00:1a:30:38:a8:00 REACHABLE
10.10.29.74 dev eth0 lladdr 00:30:48:8e:31:ac REACHABLE
Последнее поле показывает состояние системы «определения недоступности соседа»:
- STALE — сосед существует, но, скорее всего недоступен, поэтому ядро попробует проверить это при первой ближайшей передаче.
- DELAY — пакет был отправлен соседу в состоянии STALE и ядро ждет подтверждения.
- REACHABLE — сосед существует и определенно доступен.
Добавить новую ARP запись
Например, добавить постоянную ARP запись для соседа 192.168.1.5 на устройстве eth0:
Состояние соседа | Значение |
---|---|
permanent | Состояние соседа занято навсегда и может быть удалено только администратором. |
noarp | Состояние соседа валидно. Попыток проверить состояние не будет, но может быть удалено, когда закончится время жизни. |
stale | Состояние соседа валидно, но подозрительно. Эта опция для ip neigh не меняет состояние соседа, если оно было валидно и адрес не был изменен этой командой. |
reachable | Состояние соседа валидно до окончания таймаута доступности. |
Удалить ARP запись
Удалить запись для соседа 192.168.1.5 на интерфейсе eth1:
Изменить состояние на reachable для соседа 192.168.1.100 на устройстве eth1:
Очистить ARP запись
Команда flush или f очищает таблицы соседей или arp таблицы. Синтаксис:
ip route: команды управления таблицей маршрутизации
Используйте следующие команды для управления таблицей маршрутизации ядра.
Показать таблицу маршрутизации
Посмотреть таблицу маршрутизации:
Показать роутинг для 192.168.1.0/24:
192.168.1.0/24 dev eth1 proto kernel scope link src 192.168.1.10
Добавить новый маршрут
Добавить статический маршрут в сеть 192.168.1.0/24 через шлюз 192.168.1.254:
Чтобы маршрутизировать весь трафик через шлюз 192.168.1.254 подключенный через сетевой интерфейс eth0:
Удалить маршрут
Команда чтобы удалить маршрут по умолчанию:
В этом примере удалим маршрут созданный в предыдущем блоке:
Источник
How to Set Static IP Address and Configure Network in Linux
If you are a Linux system administrator, time will come when you will need to configure networking on your system. Unlike desktop machines where you can use dynamic IP addresses, on a server infrastructure, you will need to setup a static IP address (at least in most cases).
This article is meant to show you how to configure static IP address on most frequently used Linux distributions.
For the purpose of this tutorial, we will use the following Internet Protocol version 4 (IPv4) details:
Configure Static IP Address in RHEL/CentOS/Fedora:
To configure static IP address in RHEL / CentOS / Fedora, you will need to edit:
Where in the above «ifcfg-eth0″ answers to your network interface eth0 . If your interface is named “ eth1» then the file that you will need to edit is «ifcfg-eth1» .
Let’s start with the first file:
Open that file and set:
Note: Make sure to open the file corresponding to your network interface. You can find your network interface name with ifconfig -a command.
In that file make the following changes:
You will only need to edit the settings for:
Other settings should have already been predefined.
Next edit resolve.conf file by opening it with a text editor such as nano or vi:
Once you have made your changes restart the networking with:
Set Static IP Address in Debian / Ubuntu
To setup static IP address in Debian/ Ubuntu, open the following file:
You may see a line looking like this:
Change it so it looks like this:
Save the file and then edit /etc/resolv.conf like this:
Restart the networking on your system with:
Your static IP address has been configured.
Conclusion:
You now know how to configure a static IP address on a Linux distro. If you have any questions or comments, please do not hesitate to submit them in the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
10 Useful “IP” Commands to Configure Network Interfaces
The ip command is a new networking command-line utility that is used to assign an IP address to a network interface or configure/update useful network variables on a Linux system.
It is a part of the iproute2 package and offers several network administration tasks such as bringing up or down network interfaces, assign and remove IP addresses and routes, manage ARP cache, and much more.
The ip command is much similar to the old ifconfig command, but it is greatly more powerful with more functions and capabilities added to it.
The ifconfig command has been deprecated and replaced by the ip command in all modern Linux distributions. However, the ifconfig command is still works and available for most Linux distributions.
10 IP Command Examples
Note: Please take configuration file backup before doing any changes.
How Do I Configure Static IP Address Internet Protocol (IPv4)
To configure static IP Addresses in Linux, you need to update or edit the network configuration file to assign a Static IP Address to a system. You must be a superuser with a su (switch user) command from the terminal or command prompt.
For RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux
Open and edit the network configuration files for (eth0 or eth1) using your favorite text editor. For example, assigning IP Address to eth0 interface as follows.
Simple output:
For Ubuntu/Debian/Linux Mint
Assign Static IP Address to eth0 interface editing configuration file /etc/network/interfaces to make permanent changes as shown below.
Next, restart network services after entering all the details using the following command.
1. How to Assign an IP Address to a Specific Interface
The following command is used to assign an IP Addresses to a specific interface (eth1) on the fly.
Note: Unfortunately all these settings will be lost after a system restart.
2. How to Check an IP Address
To get the depth information of your network interfaces like IP Address, MAC Address information, use the following command as shown below.
Sample Output
3. How to Remove an IP Address
The following command will remove an assigned IP address from the given interface (eth1).
4. How to Enable Network Interface
The “up” flag with interface name (eth1) enables a network interface. For example, the following command will activate the eth1 network interface.
5. How to Disable Network Interface
The “down” flag with interface name (eth1) disables a network interface. For example, the following command will De-activates the eth1 network interface.
6. How do I Check Route Table?
Type the following command to check the routing table information of the system.
Sample Output
7. How do I Add Static Route
Why do you need to add Static routes or Manual routes, because that the traffic must not pass through the default gateway. We need to add Static routes to pass traffic from the best way to reach the destination.
8. How to Remove Static Route
To remove the assigned static route, simply type the following command.
9. How do I Add Persistence Static Routes
All the above routes will be lost after a system restart. To add permanent Static route, edit file /etc/sysconfig/network-scripts/route-eth0 (We are storing static route for (eth0).
For RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux
and add the following lines and save and exit. By default route-eth0 file will not be there, need to be created.
For Ubuntu/Debian/Linux Mint
Open the file /etc/network/interfaces and at the end add the persistence Static routes. IP Addresses may differ in your environment.
Next, restart network services after entering all the details using the following command.
10. How do I Add Default Gateway
The default gateway can be specified globally or for interface-specific config files. The advantage of the default gateway is If we have more than one NIC is present in the system. You can add the default gateway on the fly as shown below the command.
Kindly correct me if I missed out. Please refer manual page doing man ip from terminal/command prompt to know more about IP Command.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник