Netplan io что это
Перейти к содержимому

Netplan io что это

  • автор:

Пакет: (0.99-0ubuntu1)

Please consider filing a bug or asking a question via Launchpad before contacting the maintainer directly.

Original Maintainers (usually from Debian):

  • Debian netplan Maintainers
  • Andrej Shadura
  • Mathieu Trudel-Lapierre

It should generally not be necessary for users to contact the original maintainer.

Внешние ресурсы:

Подобные пакеты:

YAML network configuration abstraction for various backends

Другие пакеты, относящиеся к

  • зависимости
  • рекомендации
  • предложения
  • enhances
  • sug: network-manager network management framework (daemon and userspace tools) или wpasupplicant client support for WPA and WPA2 (IEEE 802.11i)


Загрузить для всех доступных архитектур

Архитектура Размер пакета В установленном виде Файлы
amd64 69,1 Кб 280,0 Кб [список файлов]
arm64 67,7 Кб 272,0 Кб [список файлов]
armhf 67,4 Кб 262,0 Кб [список файлов]
ppc64el 68,9 Кб 352,0 Кб [список файлов]
riscv64 67,1 Кб 268,0 Кб [список файлов]
s390x 67,5 Кб 280,0 Кб [список файлов]

This page is also available in the following languages:

Авторские права © 2023 Canonical Ltd.; См. условия лицензии. Ubuntu это торговый знак компании Canonical Ltd. Об этом сайте.


See netplan help for a list of available commands on this system.



Distribution installers, cloud instantiation, image builds for particular devices, or any other way to deploy an operating system put its desired network configuration into YAML configuration file(s). During early boot, the netplan “network renderer” runs which reads //netplan/*.yaml and writes configuration to /run to hand off control of devices to the specified networking daemon.

• Configured devices get handled by systemd-networkd by default, unless explicitly marked as managed by a specific renderer (NetworkManager) • Devices not covered by the network config do not get touched at all. • Usable in initramfs (few dependencies and fast) • No persistent generated config, only original YAML config • Parser supports multiple config files to allow applications like libvirt or lxd to package up expected network config (virbr0, lxdbr0), or to change the global default policy to use NetworkManager for everything. • Retains the flexibility to change backends/policy later or adjust to removing NetworkManager, as generated configuration is ephemeral.

General structure¶

netplan’s configuration files use the YAML ( format. All //netplan/*.yaml are considered. Lexicographically later files (regardless of in which directory they are) amend (new mapping keys) or override (same mapping keys) previous ones. A file in /run/netplan completely shadows a file with same name in /etc/netplan, and a file in either of those directories shadows a file with the same name in /lib/netplan.

The top-level node in a netplan configuration file is a network: mapping that contains version: 2 (the YAML currently being used by curtin, MaaS, etc. is version 1), and then device definitions grouped by their type, such as ethernets:, modems:, wifis:, or bridges:. These are the types that our renderer can understand and are supported by our backends.

Each type block contains device definitions as a map where the keys (called “configuration IDs”) are defined as below.

Device configuration IDs¶

The key names below the per-device-type definition maps (like ethernets:) are called “ID”s. They must be unique throughout the entire set of configuration files. Their primary purpose is to serve as anchor names for composite devices, for example to enumerate the members of a bridge that is currently being defined.

(Since 0.97) If an interface is defined with an ID in a configuration file; it will be brought up by the applicable renderer. To not have netplan touch an interface at all, it should be completely omitted from the netplan configuration files.

There are two physically/structurally different classes of device definitions, and the ID field has a different interpretation for each:

Physical devices (Examples: ethernet, modem, wifi) These can dynamically come and go between reboots and even during runtime (hotplugging). In the generic case, they can be selected by match: rules on desired properties, such as name/name pattern, MAC address, driver, or device paths. In general these will match any number of devices (unless they refer to properties which are unique such as the full path or MAC address), so without further knowledge about the hardware these will always be considered as a group.

It is valid to specify no match rules at all, in which case the ID field is simply the interface name to be matched. This is mostly useful if you want to keep simple cases simple, and it’s how network device configuration has been done for a long time.

If there are match: rules, then the ID field is a purely opaque name which is only being used for references from definitions of compound devices in the config.

Common properties for physical device types¶

• all cards on second PCI bus:

Any supported network device that is declared with the openvswitch mapping (or any bond/bridge that includes an interface with an openvswitch configuration) will be created in openvswitch instead of the defined renderer. In the case of a vlan definition declared the same way, netplan will create a fake VLAN bridge in openvswitch with the requested vlan properties.

external-ids (mapping) – since 0.100 Passed-through directly to OpenVSwitch other-config (mapping) – since 0.100 Passed-through directly to OpenVSwitch lacp (scalar) – since 0.100 Valid for bond interfaces. Accepts active, passive or off (the default). fail-mode (scalar) – since 0.100 Valid for bridge interfaces. Accepts secure or standalone (the default). mcast-snooping (bool) – since 0.100 Valid for bridge interfaces. False by default. protocols (sequence of scalars) – since 0.100 Valid for bridge interfaces or the network section. List of protocols to be used when negotiating a connection with the controller. Accepts OpenFlow10, OpenFlow11, OpenFlow12, OpenFlow13, OpenFlow14, OpenFlow15 and OpenFlow16. rstp (bool) – since 0.100 Valid for bridge interfaces. False by default. controller (mapping) – since 0.100 Valid for bridge interfaces. Specify an external OpenFlow controller.

Common properties for all device types¶

(Since 0.99) The renderer property has one additional acceptable value for vlan objects (i. e. defined in vlans:): sriov. If a vlan is defined with the sriov renderer for an SR-IOV Virtual Function interface, this causes netplan to set up a hardware VLAN filter for it. There can be only one defined per VF.

If you are in an IPv6-only environment with completely stateless autoconfiguration (SLAAC with RDNSS), this option can be set to cause the interface to be brought up. (Setting accept-ra alone is not sufficient.) Autoconfiguration will still honour the contents of the router advertisement and only use DHCP if requested in the RA.

Note that rdnssd (8) is required to use RDNSS with networkd. No extra software is required for NetworkManager.

Requires feature: ipv6-mtu

This feature enables or disables link-local addresses for a protocol, but the actual implementation differs per backend. On networkd, this directly changes the behavior and may add an extra address on an interface. When using the NetworkManager backend, enabling link-local has no effect if the interface also has DHCP enabled.

Example to enable only IPv4 link-local: link-local: [ ipv4 ] Example to enable all link-local addresses: link-local: [ ipv4, ipv6 ] Example to disable all link-local addresses: link-local: [ ]

For virtual devices (bridges, bonds, vlan) if there is no address configured and DHCP is disabled, the interface may still be brought online, but will not be addressable from the network.

In addition to the addresses themselves one can specify configuration parameters as mappings. Current supported options are:

lifetime (scalar) – since 0.100 Default: forever. This can be forever or 0 and corresponds to the PreferredLifetime option in systemd-networkd’s Address section. Currently supported on the networkd backend only. label (scalar) – since 0.100 An IP address label, equivalent to the ip address label command. Currently supported on the networkd backend only.

Example: addresses: [, "2001:1::1/64"]

Example for IPv4: gateway4: Example for IPv6: gateway6: "2001:4::1"

Note: This will not work reliably for devices matched by name only and rendered by networkd, due to interactions with device renaming in udev. Match devices by MAC when setting MAC addresses.

Note: This will not work reliably for devices matched by name only and rendered by networkd, due to interactions with device renaming in udev. Match devices by MAC when setting MTU.

DHCP Overrides¶

Several DHCP behavior overrides are available. Most currently only have any effect when using the networkd backend, with the exception of use-routes and route-metric.

Overrides only have an effect if the corresponding dhcp4 or dhcp6 is set to true.

If both dhcp4 and dhcp6 are true, the networkd backend requires that dhcp4-overrides and dhcp6-overrides contain the same keys and values. If the values do not match, an error will be shown and the network configuration will not be applied.

When using the NetworkManager backend, different values may be specified for dhcp4-overrides and dhcp6-overrides, and will be applied to the DHCP client processes as specified in the netplan YAML.

dhcp4-overrides , dhcp6-overrides (mapping) The dhcp4-overrides and dhcp6-overrides mappings override the default DHCP behavior.

Requires feature: dhcp-use-domains


Complex routing is possible with netplan. Standard static routes as well as policy routing using routing tables are supported via the networkd backend.

These options are available for all types of interfaces.

routes (mapping) The routes block defines standard static routes for an interface. At least to and via must be specified.

For from, to, and via, both IPv4 and IPv6 addresses are recognized, and must be in the form addr/prefixlen or addr.

from (scalar) Set a source IP address for traffic going through the route. (NetworkManager: as of v1.8.0) to (scalar) Destination address for the route. via (scalar) Address to the gateway to use for this route. on-link (bool) When set to “true”, specifies that the route is directly connected to the interface. (NetworkManager: as of v1.12.0 for IPv4 and v1.18.0 for IPv6) metric (scalar) The relative priority of the route. Must be a positive integer value. type (scalar) The type of route. Valid options are “unicast” (default), “unreachable”, “blackhole” or “prohibit”. scope (scalar) The route scope, how wide-ranging it is to the network. Possible values are “global”, “link”, or “host”. NetworkManager does not support setting a scope. table (scalar) The table number to use for the route. In some scenarios, it may be useful to set routes in a separate routing table. It may also be used to refer to routing policy rules which also accept a table parameter. Allowed values are positive integers starting from 1. Some values are already in use to refer to specific routing tables: see /etc/iproute2/rt_tables. (NetworkManager: as of v1.10.0) mtu (scalar) – since 0.101 The MTU to be used for the route, in bytes. Must be a positive integer value.

For from, to, both IPv4 and IPv6 addresses are recognized, and must be in the form addr/prefixlen or addr.

from (scalar) Set a source IP address to match traffic for this policy rule. to (scalar) Match on traffic going to the specified destination. table (scalar) The table number to match for the route. In some scenarios, it may be useful to set routes in a separate routing table. It may also be used to refer to routes which also accept a table parameter. Allowed values are positive integers starting from 1. Some values are already in use to refer to specific routing tables: see /etc/iproute2/rt_tables. priority (scalar) Specify a priority for the routing policy rule, to influence the order in which routing rules are processed. A higher number means lower priority: rules are processed in order by increasing priority number. mark (scalar) Have this routing policy rule match on traffic that has been marked by the iptables firewall with this value. Allowed values are positive integers starting from 1. type-of-service (scalar) Match this policy rule based on the type of service number applied to the traffic.


Netplan supports advanced authentication settings for ethernet and wifi interfaces, as well as individual wifi networks, by means of the auth block.

auth (mapping) Specifies authentication settings for a device of type ethernets:, or an access-points: entry on a wifis: device.

The auth block supports the following properties:

key-management (scalar) The supported key management modes are none (no key management); psk (WPA with pre-shared key, common for home wifi); eap (WPA with EAP, common for enterprise wifi); and 802.1x (used primarily for wired Ethernet connections). password (scalar) The password string for EAP, or the pre-shared key for WPA-PSK.

The following properties can be used if key-management is eap or 802.1x:

method (scalar) The EAP method to use. The supported EAP methods are tls (TLS), peap (Protected EAP), and ttls (Tunneled TLS). identity (scalar) The identity to use for EAP. anonymous-identity (scalar) The identity to pass over the unencrypted channel if the chosen EAP method supports passing a different tunnelled identity. ca-certificate (scalar) Path to a file with one or more trusted certificate authority (CA) certificates. client-certificate (scalar) Path to a file containing the certificate to be used by the client during authentication. client-key (scalar) Path to a file containing the private key corresponding to client-certificate. client-key-password (scalar) Password to use to decrypt the private key specified in client-key if it is encrypted. phase2-auth (scalar) – since 0.99 Phase 2 authentication mechanism.

Properties for device type ethernets:¶

Ethernet device definitions, beyond common ones described above, also support some additional properties that can be used for SR-IOV devices.

link (scalar) – since 0.99 (SR-IOV devices only) The link property declares the device as a Virtual Function of the selected Physical Function device, as identified by the given netplan id.

virtual-function-count (scalar) – since 0.99 (SR-IOV devices only) In certain special cases VFs might need to be configured outside of netplan. For such configurations virtual-function-count can be optionally used to set an explicit number of Virtual Functions for the given Physical Function. If unset, the default is to create only as many VFs as are defined in the netplan configuration. This should be used for special cases only.

Requires feature: sriov

Properties for device type modems:¶

GSM/CDMA modem configuration is only supported for the NetworkManager backend. systemd-networkd does not support modems.

Requires feature: modems

apn (scalar) – since 0.99 Set the carrier APN (Access Point Name). This can be omitted if auto-config is enabled. auto-config (bool) – since 0.99 Specify whether to try and autoconfigure the modem by doing a lookup of the carrier against the Mobile Broadband Provider database. This may not work for all carriers. device-id (scalar) – since 0.99 Specify the device ID (as given by the WWAN management service) of the modem to match. This can be found using mmcli. network-id (scalar) – since 0.99 Specify the Network ID (GSM LAI format). If this is specified, the device will not roam networks. number (scalar) – since 0.99 The number to dial to establish the connection to the mobile broadband network. (Deprecated for GSM) password (scalar) – since 0.99 Specify the password used to authenticate with the carrier network. This can be omitted if auto-config is enabled. pin (scalar) – since 0.99 Specify the SIM PIN to allow it to operate if a PIN is set. sim-id (scalar) – since 0.99 Specify the SIM unique identifier (as given by the WWAN management service) which this connection applies to. If given, the connection will apply to any device also allowed by device-id which contains a SIM card matching the given identifier. sim-operator-id (scalar) – since 0.99 Specify the MCC/MNC string (such as “310260” or “21601”) which identifies the carrier that this connection should apply to. If given, the connection will apply to any device also allowed by device-id and sim-id which contains a SIM card provisioned by the given operator. username (scalar) – since 0.99 Specify the username used to authentiate with the carrier network. This can be omitted if auto-config is enabled.

Properties for device type wifis:¶

Note that systemd-networkd does not natively support wifi, so you need wpasupplicant installed if you let the networkd renderer handle wifi.

access-points (mapping) This provides pre-configured connections to NetworkManager. Note that users can of course select other access points/SSIDs. The keys of the mapping are the SSIDs, and the values are mappings with the following supported properties:

is equivalent to

Properties for device type bridges:¶

Properties for device type bonds:¶

For historical reasons, the misspelling gratuitious-arp is also accepted and has the same function.

This parameter specifies how many IGMP membership reports are issued on a failover event. Values range from 0 to 255. 0 disables sending membership reports. Otherwise, the first membership report is sent on failover and subsequent reports are sent at 200ms intervals.

Properties for device type tunnels:¶

Tunnels allow traffic to pass as if it was between systems on the same local network, although systems may be far from each other but reachable via the Internet. They may be used to support IPv6 traffic on a network where the ISP does not provide the service, or to extend and “connect” separate local networks. Please see for more general information about tunnels.

mode (scalar) Defines the tunnel mode. Valid options are sit, gre, ip6gre, ipip, ipip6, ip6ip6, vti, vti6 and wireguard. Additionally, the networkd backend also supports gretap and ip6gretap modes. In addition, the NetworkManager backend supports isatap tunnels. local (scalar) Defines the address of the local endpoint of the tunnel. remote (scalar) Defines the address of the remote endpoint of the tunnel. key (scalar or mapping) Define keys to use for the tunnel. The key can be a number or a dotted quad (an IPv4 address). For wireguard it can be a base64-encoded private key or (as of networkd v242+) an absolute path to a file, containing the private key (since 0.100). It is used for identification of IP transforms. This is only required for vti and vti6 when using the networkd backend, and for gre or ip6gre tunnels when using the NetworkManager backend.

This field may be used as a scalar (meaning that a single key is specified and to be used for input, output and private key), or as a mapping, where you can further specify input/output/private.

input (scalar) The input key for the tunnel output (scalar) The output key for the tunnel private (scalar) – since 0.100 A base64-encoded private key required for Wireguard tunnels. When the systemd-networkd backend (v242+) is used, this can also be an absolute path to a file containing the private key.

Wireguard specific keys:

mark (scalar) – since 0.100 Firewall mark for outgoing WireGuard packets from this interface, optional. port (scalar) – since 0.100 UDP port to listen at or auto. Optional, defaults to auto. peers (sequence of mappings) – since 0.100 A list of peers, each having keys documented below.

endpoint (scalar) – since 0.100 Remote endpoint IPv4/IPv6 address or a hostname, followed by a colon and a port number. allowed-ips (sequence of scalars) – since 0.100 A list of IP (v4 or v6) addresses with CIDR masks from which this peer is allowed to send incoming traffic and to which outgoing traffic for this peer is directed. The catch-all may be specified for matching all IPv4 addresses, and ::/0 may be specified for matching all IPv6 addresses. keepalive (scalar) – since 0.100 An interval in seconds, between 1 and 65535 inclusive, of how often to send an authenticated empty packet to the peer for the purpose of keeping a stateful firewall or NAT mapping valid persistently. Optional. keys (mapping) – since 0.100 Define keys to use for the Wireguard peers.

This field can be used as a mapping, where you can further specify the public and shared keys.

public (scalar) – since 0.100 A base64-encoded public key, requried for Wireguard peers. shared (scalar) – since 0.100 A base64-encoded preshared key. Optional for Wireguard peers. When the systemd-networkd backend (v242+) is used, this can also be an absolute path to a file containing the preshared key.

Properties for device type vlans:¶

Backend-specific configuration parameters¶

In addition to the other fields available to configure interfaces, some backends may require to record some of their own parameters in netplan, especially if the netplan definitions are generated automatically by the consumer of that backend. Currently, this is only used with NetworkManager.

networkmanager (mapping) – since 0.99 Keeps the NetworkManager-specific configuration parameters used by the daemon to recognize connections.


Configure an ethernet device with networkd, identified by its name, and enable DHCP:

This is an example of a static-configured interface with multiple IPv4 addresses and multiple gateways with networkd, with equal route metric levels, and static DNS nameservers (Google DNS for this example):

Name already in use

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats


Failed to load latest commit information.

netplan — Backend-agnostic network configuration in YAML

An overview of the architecture can be found at

The full documentation for netplan is available in the doc/ directory.

Build using Meson

Steps to build netplan using the Meson build system inside the build/ directory:

Настройка сети Netplan в Ubuntu

Начиная с релиза Ubuntu 17.10, для управления конфигурацией сети используется утилита Netplan. Раньше для этих целей применялся скрипт ifupdown, конфигурационные файлы которого находились в папке /etc/network/interfaces. Недостатком такого подхода было то, что файлы настройки сети были разбросаны по всей системе, частью настроек мог управлять NetworkManager, частью systemd-networkd, а часть вообще делалась с помощью ifupdown.

Новая система конфигурации позволяет таки сложить все яйца в одну корзину. Вы выполняете настройку в формате YAML, а Netplan автоматически преобразовывает её при запуске в конфигурацию той системы, которую вы выбрали. В этой статье мы рассмотрим, как выполняется настройка сети Netplan в Ubuntu 18.04.

Основы использования Netplan

Все конфигурационные файлы Netplan находятся в папке /etc/netplan/. Во время запуска службы, она преобразовывает свою конфигурацию в конфигурацию той службы, которая будет управлять сетью и помещает её в каталог /run/. По умолчанию в Ubuntu есть только один конфигурационный файл со следующим содержимым:

Это означает, что управление всей сетью передаётся утилите NetworkManager. Чтобы разобраться, что это означает, давайте рассмотрим синтаксис конфигурационного файла.

1. Синтаксис конфигурации Netplan

Новичкам синтаксис конфигурационного файла Netplan может показаться запутанным, но разобраться в нём вполне можно. Он чем-то напоминает JSON, но не имеет таких жёстких ограничений:

поле0 :
поле1 : значение
поле2 :
— элемент1
— элемент2
— элемент3

Имя поля и его значение разделяется двоеточием. В качестве значения поля можно передавать не только текстовое или числовое значение, но и другое поле, несколько полей или список значений. При передаче списка каждый новый элемент списка должен начинаться с дефиса. Табуляции использовать нельзя. Отступы используются для указания структуры. Например, из примера видно, что поле1 и поле2 относятся к полю0. Это всё, что касается общего синтаксиса, теперь про Netplan:

network :
version : 2
renderer : программа_бэкенд
вид_интерфейса :
имя_интерфейса :
параметр : значение

Первые две строчки конфигурации стандартны. Первая указывает, что мы будем иметь дело с сетью, а вторая указывает версию стандарта конфигурации, которая будет использоваться. Их лучше не трогать.

  • renderer — указывает программу, для которой будут преобразоваться ваши настройки. На данный момент поддерживаются только network-manager и systemd-networkd;
  • вид_интерфейса — вид сетевых интерфейсов, которые вы будете настраивать в этой секции. Они делятся на физические: ethernets (проводные), wifis (беспроводные) и виртуальные: vlans , bonds, bridges.
  • имя_интерфейса — имя сетевого интерфейса в системе, например enp3s0 или eth0;
  • параметры — настройки, с помощью которых указывается, как нужно подключаться к сети.

2. Параметры Netplan

Мы разобрались с основным синтаксисом, далее разберём команды, с помощью которых мы будем настраивать сеть:

  • renderer — программа для обработки конфигурации;
  • dhcp4 — получение IPv4 адреса по DHCP;
  • dhcp6 — получение IPv6 адреса по DHCP;
  • dhcp-identifier — если передать значение «mac», то будет использоваться MAC-адрес в качестве идентификатора DHCP;
  • addresses — добавляет статические адреса к интерфейсу, можно несколько;
  • gateway4 — указывает шлюз IPv4;
  • gateway6 — указывает шлюз IPv6;
  • nameservers — указывает DNS-серверы;
  • macaddress — устанавливает новый MAC-адрес;
  • routes — позволяет настроить маршруты таблицы маршрутизации;
  • routing-policy — дополнительная настройка маршрутов, для IP или подсети;
  • access-points — список точек доступа для Wi-Fi;
  • password — пароль для точки доступа Wi-Fi;
  • mode — режим работы сетевой карты Wi-Fi.

3. Команды Netplan

Синтаксис самой команды netplan очень прост:

netplan опции команда

В качестве команды можно передать одну из команд:

  • try — попробовать применить конфигурацию с возможностью отмены;
  • apply — применить конфигурацию;
  • generate — проверка текущей конфигурации и запись на диск;
  • config — записать текущую конфигурацию сети в YAML.

Как настроить сеть Netplan в Ubuntu

Сначала необходимо посмотреть, как называются сетевые интерфейсы в вашей системе. Для этого можно просто изучить содержимое папки /sys/class/net:

У меня есть только Wi-Fi-карта — wlp, у вас же может быть ещё и проводной интерфейс enp. Или устройства могут называться по старому — wlan и eth. Всё зависит от системы.

1. Настройка динамического IP в Netplan

Для настройки динамического IP- адреса для интерфейса enp3s0 создадим новый конфигурационный файл 02-networkd.yaml. Самая простая настройка Netplan для получения IP по DHCP будет выглядеть вот так:

sudo vi /etc/netplan/02-networkd.yaml

version: 2
renderer: networkd
dhcp4: yes

В качестве программы для обработки конфигурации мы используем Networkd, далее мы указываем наш сетевой интерфейс и включаем получение IPv4 адреса по DHCP. Все остальные параметры тоже подтянутся по DHCP. Или мы можем вручную настроить DNS для этого интерфейса:

version: 2
renderer: networkd
dhcp4: yes

Теперь осталось проверить эту конфигурацию. Для этого выполните:

sudo netplan generate

Если ошибок нет, программа ничего не выведет и запишет вашу конфигурацию на диск. Если есть ошибки, утилита о них сообщит.

2. Настройка статического IP в Netplan

Статический IP-адрес в Netplan настроить немного сложнее. Поскольку здесь нам нужно будет задать не только непосредственно сам адрес, но и кучу других параметров, которые система раньше получала по DHCP. Нам надо указать шлюз для доступа в интернет и DNS-серверы. Модифицируем тот же конфигурационный файл:

sudo vi /etc/netplan/02-networkd.yaml

version: 2
renderer: networkd
dhcp4: no
addresses: [ ]
addresses: [, ]

Рассмотрим подробнее, что за что отвечает в этом конфигурационном файле.

  • dhcp4 — отключаем получение IP адреса по DHCP;
  • addresses — параметр ожидает список IP-адресов, которые нужно присвоить нашей сетевой карте, у нас только один адрес, однако, передавать его надо тоже в формате списка, иначе будет ошибка. В конце адреса указывается префикс маски — /24, который отвечает маске сети Вы можете указать и другую маску, но только с помощью префикса, отдельного параметра для этого нет.
  • gateway4 — задаёт адрес роутера, через который наш компьютер сможет получить доступ в интернет;

Остальное вы знаете. Списки можно оформлять не только с помощью черточек, для каждого пункта с новой строки, но и с помощью квадратных скобок, тогда элементы записываются в одну строку через запятую.

3. Настройка Wi-Fi через Netplan на Ubuntu

Кроме проводного подключения, система конфигурации Netplan умеет управлять подключением к Wi-Fi. Это отличная новость, учитывая, насколько сложно всё это раньше настраивалось, если не было NetworkManager. Правда, для работы Wi-Fi через Networkd надо, чтобы в системе был установлен пакет wpasupplicant. Например, у нас есть точка доступа AccessPoint с паролем 12345678? и мы хотим к ней подключаться. Тогда настройка Netplan Ubuntu будет выглядеть так:

version: 2
renderer: networkd
dhcp4: yes
dhcp6: no
addresses: [, ]
password: «12345678»

Здесь мы указываем, что надо получить IP и другие параметры по DHCP, устанавливаем DNS-сервер вручную, хотя это не обязательно, а затем добавляем точку доступа и пароль к ней.

4. Применение конфигурации netplan

Естественно, что после смены настроек в конфигурационном файле ничего не меняется. Сначала нужно проверить конфигурационный файл на ошибки и создать файлы конфигурации программы-обработчика. Для этого выполните:

sudo netplan generate

Если вы хотите видеть более подробную информацию, используйте опцию —debug:

sudo netplan —debug generate

Если есть ошибки, их надо исправить, если нет, применяем конфигурацию с помощью команды:

sudo netplan —debug apply

Если вы меняли программу-обработчик, например с NetworkManager на networkd, то надо ещё перезапустить компьютер. После этого сеть будет работать на новой конфигурации.


В этой статье мы рассмотрели, как выполняется настройка сети Netplan в Ubuntu 18.04. Как видите, это не очень сложно, и даже удобно, по сравнению со старой конфигурацией. Конечно, есть некоторые недостатки — та же самая невозможность задать маску без префикса, но программа активно развивается, возможно, в будущем это будет исправлено.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *