Network configuration tool linux

Настройка сети в Linux с помощью netplan

Обновлено

Обновлено: 16.02.2023 Опубликовано: 31.10.2019

Начиная с Ubuntu 18.04 конфигурирование сети выполняется с помощью утилиты netplan. В других системах на базе deb, например, Debian, она может быть установлена командой:

Конфигурационный файл

Файл для настройки сети находится в каталоге /etc/netplan/. Имя файла может быть любым, на конце должно быть расширение yaml, например:

* чаще всего, это файл 50-cloud-init.yaml или 01-netcfg.yaml. YAML представляет из себя текстовый формат файла. Вложенные параметры должны иметь отступы табуляциями или пробелами, количество которых имеет важное значение (если поставить лишний пробел у одного из нескольких параметров, мы получим сообщение об ошибке «expected mapping»).

Простая настройка сети

Разберем пример настройки 3-х сетевых интерфейсов. Два из них будут с IP-адресами назначенными вручную (static IP), один — по DHCP. Приводим файл к следующему виду:

network:
version: 2
renderer: networkd
ethernets:
ens3:
dhcp4: true
ens7:
dhcp4: no
addresses: [192.168.122.195/24]
routes:
#- to: 0.0.0.0/0
— to: default
via: 192.168.122.1
mtu: 1500
nameservers:
addresses: [8.8.8.8, 77.88.8.8]
search: [ dmosk.local ]
ens9:
dhcp4: no
addresses: [192.168.1.10/24, 192.168.1.20/24]
nameservers:
addresses:
— 8.8.8.8
— 77.88.8.8
search: [ dmosk.local, dmosk.ru ]

  • version — версия YAML. На момент обновления статьи, была 2.
  • renderer — менеджер сети (networkd или NetworkManager).
  • ethernets — настройка сетевых адаптеров ethernet.
  • ens3, ens7, ens9 — настройки для соответствующих сетевых адаптеров. В данном примере мы настраиваем 3 сетевых адаптера.
  • dhcp4 — будет ли получать сетевой адаптер IP-адрес автоматически. Возможны варианты yes/true — получать адрес автоматически; no/false — адрес должен быть назначен вручную.
  • addresses — задает IP-адреса через запятую.
  • routes — настройка маршрутов. Для шлюза по умолчанию используем опцию и значение to: default. Ранее использовалась директива gateway4, но теперь она считается устаревшей (при применении настройки с ней система вернет предупреждение gateway4 has been deprecated, use default routes instead). Также обратите внимание на вариант с 0.0.0.0 — в более ранних версиях системы вариат с default выдаст ошибку, и нужно использовать конфигурацию с четыремя нулями.
  • mtu — при желании, можно задать значение MTU.
  • nameservers — настройка серверов имен (DNS).
  • nameservers addresses — указываем серверы DNS. Обратите внимание на разный формат записи для ens7 и ens9. Приемлемы оба варианта.
  • nameservers search — дописывает окончание домена, если мы обращаемся к узлу сети только по его имени. Стоит обратить внимание, что мы можем указать несколько доменов через запятую.

Применение настроек

Для применения настроек необходимо запустить команду netplan. Ее синтаксис:

Для проверки нашего конфигурационного файла вводим:

Источник

NMState: A Declarative Networking Config Tool for Linux

The Linux ecosystem provides numerous ways of configuring networking including the popular Network Manager daemon and command-line tools such as nmcli and nmtui GUI utility. This guide introduces yet another network configuration tool known as NMState

Читайте также:  Linux быстрое удаление большого количества файлов

NMState is a declarative network manager for configuring networking on Linux hosts. It’s a library that provides a command-line tool that manages host network settings. It manages host networking through a northbound declarative API. At the time of writing this guide, the NetworkManager daemon is the only provider supported by NMState.

In this guide, we look at some of the example usages of the NMState tool. For this guide, we will demonstrate this using Fedora Linux.

Imperative vs Declarative Approaches

Network management can take two approaches – Imperative and declarative. In the imperative approach, you explicitly define the networking state of an interface by running commands on the terminal. The focus is on the ‘how’.

For example, to bring down a network using the imperative approach, run the command:

$ sudo ifconfig enp0s3 down

On the other hand, the declarative approach uses a YAML file to apply the changes to a configuration. Most DevOps orchestration tools such as Kubernetes use this approach to deploy pods applications using a YAML file.

This approach provides what is commonly referred to as Infrastructure as Code (IaC) in DevOps circles. This enhances the automation of network configuration on the host and provides a fast and more reliable way of making multiple changes to a network interface with minimal errors.

Now, let us switch gears and see how you can use the NMState configuration tool to configure your network interfaces in Linux.

Step 1: Install NMState Networking Config Tool

We will get the ball rolling by installing the Nmstate. First, check the availability of the package from Fedora repositories as follows:

From the output, we can see that the network manager is available on the official repositories.

Check NMState Package

Next, install NMstate as follows. This works on Fedora 31 and later versions.

The command installs the NMState network manager API alongside other Python dependencies.

Install NMState in Fedora

Once the installation is complete, verify the nmstate package is installed as follows.

Verify NMState Package

For RHEL-based Linux, enable the copr repository first.

$ sudo dnf copr enable nmstate/nmstate-stable

Then install NMstate as follows.

Check out additional instructions on how to install NMState from the source.

Once installed, you can check the version of NMstate installed as follows.

Using NMState Configuration Tool in Linux

With NMstate installed, let us get down to the Knitty-gritties of how you can make the most of the Network manager API.

To view the current network configuration of your network interface, run the following command. Here, is the configuration of your enp0s3 interface.

Show Network Interface Configuration

The output is divided into 4 distinct sections:

  • dns-resolver: This section contains the nameserver configuration for the particular interface.
  • route-rules: This stipulates the routing rules.
  • routes: This includes both dynamic and static routes.
  • Interfaces: This section specifies both the ipv4 and ipv6 settings.

Changing Network Configuration in Linux

You can use the NMState configuration tool to configure your hosts to the desired state using either interactive or file-based modes.

  • Interactive: This edits a network interface using the nmstatectl edit command. This command opens a text editor which is defined by the EDITOR environment variable. Once the changes are saved, NMState applies the new configuration immediately unless syntax errors were detected.
  • File-based: In file-based mode, the interface configuration is applied using a YAML or JSON file using the nmstatectl apply command.
Читайте также:  Scp linux указать порт

Let us now get our hands dirty and check out how you can modify network configuration using NMState.

Our Fedora system has two active network interfaces with the following configuration:

Sample Output
lo UNKNOWN 127.0.0.1/8 enp0s3 UP 192.168.2.104/24 enp0s8 UP 192.168.2.103/24

Interactive Configuration Mode Example

We will use interactive mode to change the MTU (Maximum Transmission Unit) of the enp0s3 network interface. By default, this is set to 1500 as shown.

Check Network MTU in Linux

We will change this to 4000. We will do so using the nmstatectl edit command as follows.

$ sudo nmstatectl edit enp0s3

This opens the configuration in a text editor. For our case, it opens in vim editor. Next, scroll all the way down and locate the mtu parameter. We will change the value to 4000, just as we would edit a file in vim. Then we will save the changes.

Change Network MTU in Linux

When you save and exit the file, you will see some scrambled output on the terminal as NMstate saves the changes. No intervention is required so, just sit still.

Let us now confirm that the change was made.

From the terminal output, we can see that we have successfully changed the MTU to 4000 from the default 1500 value.

Verify Network MTU in Linux

File-based Configuration Mode Example

Let us now modify the configuration using file-based mode. In this example, we are going to disable IPv6 for the enp0s8 network interface. The first step is to create a YAML file that will specify the desired state of the enp0s8 network interface.

$ sudo nmstatectl show enp0s8 > enp0s8.yml

Create Network YAML File

Next, we will edit the YAML file as follows.

Scroll down to the ipv6 section. To disable IPv6, set the enabled parameter to false and delete the lines that have been struck through.

Disable IPv6 in Linux

Save the configuration and apply the new state using the YAML file as follows.

$ sudo nmstatectl apply enp0s8.yml

Now run the command shown to verify that IPv6 has been disabled. The output displayed shows that the IPv6 for the enp0s8 network interface is blank, implying that we have successfully disabled IPv6 on the interface.

Confirm IPv6 Disabled in Linux

Applying Network Changes Temporarily

Another really handy functionality that NMstate provides is the ability to temporarily configure a desired networking state. Once you are satisfied with the configuration, you can proceed and make the changes permanent. Otherwise, the changes made will roll back to the initial settings once the timeout expires. The default timeout is 60 seconds.

Читайте также:  Linux error reading lock file

To demonstrate this, we will temporarily set a static IP on the enp0s3 interface and disable DHCP. Once again, access the file using a text editor.

Scroll to the ipv4 section. Specify the static IP – in our case 192.168.2.150 and delete the lines that have been struck-through. In addition, be sure to set the dhcp parameter to false.

Set Static IP in Linux

Save the file and temporarily commit the changes as follows.

$ sudo nmstatectl apply --no-commit --timeout 20 enp0s3.yml

The —no-commit option temporarily applies the changes for a period defined by the —timeout option which, in this example, is 20 seconds.

To verify the temporal application of the changes, we will check the IP configuration in a time interval of 20 seconds.

From the output, you can see that the interface IP configuration reverted to DHCP after the time interval of 20 seconds. The IP address went back to 192.168.2.104 from the earlier statically configured IP which was 192.168.2.150.

Check Network Interface

Admittedly, the NMState tool is a convenient tool for configuring your network interfaces. It is a declarative tool that applies the desired configuration state of a host’s interface using the NetworkManager API.

The state is easily defined using either the interactive approach or using the file-based method that uses a pre-configured YAML file. This enhances the automation of configuration tasks and reduction of errors during configuration.

Источник

Netplan

Netplan is a utility for easily configuring networking on a linux system. You simply create a YAML description of the required network interfaces and what each should be configured to do. From this description Netplan will generate all the necessary configuration for your chosen renderer tool.

How does it work?

Netplan reads network configuration from /etc/netplan/*.yaml which are written by administrators, installers, cloud image instantiations, or other OS deployments. During early boot, Netplan generates backend specific configuration files in /run to hand off control of devices to a particular networking daemon.

Netplan currently works with these supported renderers

How do I use it?

Configuration

Without configuration, Netplan will not do anything. The simplest configuration snippet (to bring up things via DHCP on workstations) is as follows:

network: version: 2 renderer: NetworkManager

This will make Netplan hand over control to NetworkManager, which will manage all devices in its default way (i.e. any ethernet device will come up with DHCP once carrier is detected).

When individual interface configurations are given, it will not let devices automatically come up using DHCP, but each interface needs to be specified in a file in /etc/netplan/ with its explicit YAML settings for the networkd or NetworkManager backend renderers.

Commands

Netplan uses a set of subcommands to drive its behavior:

  • netplan generate: Use /etc/netplan to generate the required configuration for the renderers.
  • netplan apply: Apply all configuration for the renderers, restarting them as necessary.
  • netplan try: Apply configuration and wait for user confirmation; will roll back if network is broken or no confirmation is given.

Источник

Оцените статью
Adblock
detector