- NetworkManager
- Features
- Documentation
- Wired Networks are Unmanaged
- Enabling Interface Management
- «Auto Ethernet» and «Auto eth0»
- SYNOPSIS
- FILE FORMAT
- MAIN SECTION
- KEYFILE SECTION
- IFUPDOWN SECTION
- LOGGING SECTION
- Настройка Network Manager в консоли
- Собираем информацию о системе
- Синтаксис и опции nmcli
- Настройка сети с помощью nmcli
- 1. Запустить NetworkManager
- 2. Список подключений
- 3. Управление подключениями
- 4. Создание DHCP соединения
- 5. Создание соединения с статическим адресом
- 6. Настройка подключения
- 7. Настройка Wifi
- Выводы
- NetworkManager
NetworkManager attempts to keep an active network connection available at all times.
The point of NetworkManager is to make networking configuration and setup as painless and automatic as possible. If using DHCP, NetworkManager is intended to replace default routes, obtain IP addresses from a DHCP server and change nameservers whenever it sees fit. In effect, the goal of NetworkManager is to make networking Just Work .
Whilst it was originally targeted at desktops, it has more recently been chosen as the default network management software for some non-Debian server-oriented Linux distributions. If you have special needs, the upstream’s developers would like to hear about them, but understand that NetworkManager is not intended to serve the needs of all users.
If not using Network Manager:
For basic or simple configurations (e.g. workstation), the regular way to configure the network was using interfaces configuration file at /etc/network/interfaces. Details are described in NetworkConfiguration. It still may be used.
Another way to configure: leverage on Systemd
NetworkManager is composed of two layers:
A daemon running as root: network-manager.
A front-end: nmcli and nmtui (enclosed in package network-manager), nm-tray, network-manager-gnome (nm-applet), plasma-nm.
Additionally, there are various plugins available that enable NetworkManager to handle other, special connections like different types of VPN connections.
NetworkManager will only handle interfaces not declared in /etc/network/interfaces (see README file).
NetworkManager keeps connection information on known individual networks in configuration files called profiles. Those are stored at /etc/NetworkManager/system-connections/. For options in these files refer to the manpage on nm-settings: man nm-settings or online. They can be edited (as root) using a text editor or the nm-connection-editor (enclosed in network-manager-gnome).
For changes in configuration to become effective, you may have to restart the NetworkManager daemon:
Starting with Debian 11 (bullseye), use:
Features
The features of NetworkManager are described on its homepage.
Documentation
Make sure you read the fine manual:
Wired Networks are Unmanaged
As of Debian 6.0 «Squeeze», NetworkManager does not manage any interface defined in /etc/network/interfaces by default.
Unmanaged devices means NetworkManager doesn’t handle those network devices. This occurs when two conditions are met:
The file /etc/network/interfaces contains anything about the interface, even:
And /etc/NetworkManager/NetworkManager.conf contains:
Enabling Interface Management
If you want NetworkManager to handle interfaces that are enabled in /etc/network/interfaces:
Set managed=true in /etc/NetworkManager/NetworkManager.conf.
Starting with Debian 11 (bullseye), use:
«Auto Ethernet» and «Auto eth0»
Auto Ethernet means «Select an Ethernet interface automatically»
Auto eth0 means «autoconfigure the eth0 interface».
A) Use nm-connection-editor or configure /etc/network/interfaces as described in NetworkConfiguration. Q. How can I configure DNS for NetworkManager?
A) The short answer is to use nm-connection-editor. For the long answer see the corresponding entry in NetworkConfiguration. Q. Why can’t I see NetworkManager with my new user account ?
A) Make sure human users are in the netdev group (see /usr/share/doc/network-manager-gnome/README.Debian). Q. How to setup a connection sharing («hotspot») for a wired interface ?
A) First make sure to install dnsmasq-base (but not dnsmasq unless you disable the system daemon in /etc/default/dnsmasq). Then use nm-connection-editor and setup a new profile using «shared to other computer» as the method for IPv4 (not possible from Gnome3’s gnome-control-center). This hides all the complexity (dnsmasq, iptables, sysctl). Finally, use that profile for the network interface connected to the shared network. For Wi-Fi interfaces, a hotspot functionality is provided which uses the same functionality besides setting up an ad-hoc WiFi network.
Источник
SYNOPSIS
If a default NetworkManager.conf is provided by your distribution’s packages, you should not modify it, since your changes may get overwritten by package updates. Instead, you can add additional .conf files to the /etc/NetworkManager/conf.d directory. These will be read in order, with later files overriding earlier ones. Packages might install further configuration snippets to /usr/lib/NetworkManager/conf.d. This directory is parsed first, even before NetworkManager.conf. Scripts can also put per-boot configuration into /run/NetworkManager/conf.d. This directory is parsed second, also before NetworkManager.conf. The loading of a file /run/NetworkManager/conf.d/name.conf can be prevented by adding a file /etc/NetworkManager/conf.d/name.conf. Likewise, a file /usr/lib/NetworkManager/conf.d/name.conf can be shadowed by putting a file of the same name to either /etc/NetworkManager/conf.d or /run/NetworkManager/conf.d.
NetworkManager can overwrite certain user configuration options via D-Bus or other internal operations. In this case it writes those changes to /var/lib/NetworkManager/NetworkManager-intern.conf. This file is not intended to be modified by the user, but it is read last and can shadow user configuration from NetworkManager.conf.
Certain settings from the configuration can be reloaded at runtime either by sending SIGHUP signal or via D-Bus’ Reload call.
NetworkManager does not require any configuration in NetworkManager.conf. Depending on your use case, you may remove all files to restore the default configuration (factory reset). But note that your distribution or other packages may drop configuration snippets for NetworkManager, such that they are part of the factory default.
FILE FORMAT
For keys that take a list of devices as their value, you can specify devices by their MAC addresses or interface names, or «*» to specify all devices. See the section called “Device List Format” below.
A simple configuration file looks like this:
As an extension to the normal keyfile format, you can also append a value to a previously-set list-valued key by doing:
MAIN SECTION
The default value and the number of available plugins is distro-specific. See the section called “PLUGINS” below for the available plugins. Note that NetworkManager’s native keyfile plugin is always appended to the end of this list (if it doesn’t already appear earlier in the list).
If this key is missing, it defaults to internal. If the chosen plugin is not available, clients are looked for in this order: dhclient, dhcpcd, internal.
When the default wired connection is deleted or saved to a new persistent connection by a plugin, the device is added to a list in the file /var/lib/NetworkManager/no-auto-default.state to prevent creating the default connection for that device again.
See the section called “Device List Format” for the syntax how to specify a device.
See the section called “Device List Format” for the syntax how to specify a device.
default: NetworkManager will update the hostname with the one provided via DHCP or reverse DNS lookup of the IP address on the connection with the default route or on any connection with the property hostname.only-from-default set to ‘false’. Connections are considered in order of increasing value of the hostname.priority property. In case multiple connections have the same priority, connections activated earlier are considered first. If no hostname can be determined in such way, the hostname will be updated to the last one set outside NetworkManager or to ‘localhost.localdomain’.
dhcp: this is similar to ‘default’, with the difference that after trying to get the DHCP hostname, reverse DNS lookup is not done. Note that selecting this option is equivalent to setting the property ‘hostname.from-dns-lookup’ to ‘false’ globally for all connections in NetworkManager.conf.
none: NetworkManager will not manage the transient hostname and will never set it.
If the key is unspecified, default is used, unless /etc/resolv.conf is a symlink to /run/systemd/resolve/stub-resolv.conf, /run/systemd/resolve/resolv.conf, /lib/systemd/resolv.conf or /usr/lib/systemd/resolv.conf. In that case, systemd-resolved is chosen automatically.
default: NetworkManager will update /etc/resolv.conf to reflect the nameservers provided by currently active connections. The rc-manager setting (below) controls how this is done.
dnsmasq: NetworkManager will run dnsmasq as a local caching nameserver, using «Conditional Forwarding» if you are connected to a VPN, and then update resolv.conf to point to the local nameserver. It is possible to pass custom options to the dnsmasq instance by adding them to files in the «/etc/NetworkManager/dnsmasq.d/» directory. Note that when multiple upstream servers are available, dnsmasq will initially contact them in parallel and then use the fastest to respond, probing again other servers after some time. This behavior can be modified passing the ‘all-servers’ or ‘strict-order’ options to dnsmasq (see the manual page for more details).
systemd-resolved: NetworkManager will push the DNS configuration to systemd-resolved
unbound: NetworkManager will talk to unbound and dnssec-triggerd, using «Conditional Forwarding» with DNSSEC support. /etc/resolv.conf will be managed by dnssec-trigger daemon. This option is deprecated. Note that dnssec-trigger ships a NetworkManager dispatcher script so this DNS plugin is not necessary.
none: NetworkManager will not modify resolv.conf. This implies rc-manager unmanaged
Note that the plugins dnsmasq, systemd-resolved and unbound are caching local nameservers. Hence, when NetworkManager writes /var/run/NetworkManager/resolv.conf and /etc/resolv.conf (according to rc-manager setting below), the name server there will be localhost only. NetworkManager also writes a file /var/run/NetworkManager/no-stub-resolv.conf that contains the original name servers pushed to the DNS plugin.
When using dnsmasq and systemd-resolved per-connection added dns servers will always be queried using the device the connection has been activated on.
If you configure dns=none or make /etc/resolv.conf immutable with chattr +i, NetworkManager will ignore this setting and always choose unmanaged (below).
auto: if systemd-resolved plugin is configured via the dns setting or if it gets detected as main DNS plugin, NetworkManager will update systemd-resolved without touching /etc/resolv.conf. Alternatively, if resolvconf or netconfig are enabled at compile time and the respective binary is found, NetworkManager will automatically use it. Note that if you install or uninstall these binaries, you need to reload the rc-manager setting with SIGHUP or systemctl reload NetworkManager. As last fallback it uses the symlink option (see next).
symlink: If /etc/resolv.conf is a regular file or does not exist, NetworkManager will write the file directly. If /etc/resolv.conf is instead a symlink, NetworkManager will leave it alone. Unless the symlink points to the internal file /var/run/NetworkManager/resolv.conf, in which case the symlink will be updated to emit an inotify notification. This allows the user to conveniently instruct NetworkManager not to manage /etc/resolv.conf by replacing it with a symlink.
file: NetworkManager will write /etc/resolv.conf as regular file. If it finds a symlink to an existing target, it will follow the symlink and update the target instead. In no case will an existing symlink be replaced by a file. Note that older versions of NetworkManager behaved differently and would replace dangling symlinks with a plain file.
resolvconf: NetworkManager will run resolvconf to update the DNS configuration.
netconfig: NetworkManager will run netconfig to update the DNS configuration.
unmanaged: don’t touch /etc/resolv.conf.
none: deprecated alias for symlink.
Note that this setting is complementary to the dns setting. You can keep this enabled while using dns set to another DNS plugin alongside systemd-resolved, or dns set to systemd-resolved to configure the system resolver to use systemd-resolved.
If systemd-resolved is enabled, the connectivity check resolves the hostname per-device.
RLIMIT_CORE: set ulimit -c unlimited to write out core dumps. Beware, that a core dump can contain sensitive information such as passwords or configuration settings.
fatal-warnings: set g_log_set_always_fatal() to core dump on warning messages from glib. This is equivalent to the —g-fatal-warnings command line option.
The path can also be overriden by pointing to a specific existing and writable directory. On the other hand setting this to an empty string or any other value disables the profile conversion mechanism.
This mechanism allows editing connection profile settings such as the 802.1x configuration using NetworkManager clients. Without it such changes have no effect in IWD.
KEYFILE SECTION
A device unmanaged due to this option is strictly unmanaged and cannot be overruled by using the API like nmcli device set $IFNAME managed yes. Also, a device that is unmanaged for other reasons, like an udev rule, cannot be made managed with this option (e.g. by using an except: specifier). These two points make it different from the device*.managed option which for that reason may be a better choice.
See the section called “Device List Format” for the syntax on how to specify a device.
IFUPDOWN SECTION
The default value is false.
LOGGING SECTION
In addition, these special domains can be used: NONE, ALL, DEFAULT, DHCP, IP.
Источник
Настройка Network Manager в консоли
NetworkManager — популярный инструмент управления сетевыми подключениями в Linux, имеет удобный графический интерфейс как для Gnome, так и для KDE, но бывают ситуации когда окружение рабочего стола не запускается, и нужно поднимать сеть из консоли, или нужно настроить сеть на сервере где не установлено рабочее окружение.
В этой инструкции будет рассмотрена настройка Network Manager в консоли с помощью утилиты nmcli. С настройкой в графическом интерфейсе вы разберетесь без каких-либо инструкций, поэтому была выбрана именно эта тема. Также поговорим о том, как посмотреть информацию о сетевых интерфейсах в системе.
Собираем информацию о системе
Чтобы получить информацию обо всех установленных в системе сетевых интерфейсах используйте команду:
Для просмотра статистики переданных и полученных пакетов для интерфейса, например, enp24s0, наберите:
ip -s link show enp24s0
А чтобы посмотреть таблицу маршрутизации:
ip route show match 0/0
Синтаксис и опции nmcli
Утилита nmcli — многофункциональный и гибкий инструмент командной строки для настройки сети с помощью Network Mananger из консоли. Сначала рассмотрим ее синтаксис:
$ nncli опции объект команда
Чаще всего в nmcli мы будем использовать такие объекты:
- device — управление сетевыми интерфейсами;
- connection — управление соединениями;
- networking — управление сетью в целом;
- general — показывает состояние всех сетевых протоколов и NetworkManager в целом;
- radio — управление сетевыми протоколами, wifi, ethernent и т д.
Команды для каждого объекта разные, а опции нам не будут интересны. Дальше рассмотрим примеры nmcli network manager.
Настройка сети с помощью nmcli
1. Запустить NetworkManager
Первым делом нужно запустить NetworkManager из консоли:
sudo systemctl start NetworkManager
Теперь смотрим состояние интерфейсов с помощью nmcli:
nmcli general status
Еще мы можем посмотреть имя хоста:
nmcli general hostname
Получаем состояние интерфейсов
nmcli device status
2. Список подключений
Теперь самое интересное, управление сетью nmcli. Смотрим список доступных подключений:
nmcli connection show
Здесь вы можете видеть одно проводное подключение для интерфейса enp24s0. С помощью следующей команды можно посмотреть информацию о нём:
nmcli connection show «Проводное соединение 2»
3. Управление подключениями
Чтобы подключится к сети с помощью нужного подключения используйте команду up:
nmcli connection up «Проводное соединение 2»
Команды можно сокращать, например:
nmcli conn up «Проводное соединение 2»
А для деактивации подключения используйте команду down:
nmcli conn down «Проводное соединение 2»
4. Создание DHCP соединения
Чтобы создать новое подключение используйте команду add. Например создадим новое подключение с именем dhcp:
nmcli connection add con-name «dhcp» type ethernet ifname enp24s0
Команде надо передать параметр type — тип устройства, в нашем случае ethernet (Проводное соединение), а также ifname — название сетевого интерфейса, в этом примере enp24s0. По умолчанию используется тип подключения DHCP, поэтому больше ничего настраивать не надо и вы можете уже активировать это подключение как описано выше.
5. Создание соединения с статическим адресом
Для статического подключения настроек больше, вам надо передать команде add ip адрес, который будет использоваться в качестве основного в параметре ip4, а также шлюз с помощью параметра gw4:
nmcli connection add con-name «static» ifname enp2s0 autoconnect no type ethernet ip4 192.168.0.210 gw4 192.168.0.1
6. Настройка подключения
Продолжим настройку нашего статического соединения. Обычно оно уже может работать, но вы можете захотеть добавить DNS сервер. Для этого используется команда modify:
nmcli conn modify «static» ipv4.dns 8.8.8.8
И ещё один DNS сервер с помощью оператора +:
nmcli conn modify «static» +ipv4.dns 8.8.4.4
Для добавления дополнительной информации в поле используйте символ +. Например, вот так можно добавить еще один ip адрес:
nmcli conn modify «static» +ipv4.addresses 192.168.0.240/24
Обратите внимание, что IP адрес должен быть из той же подсети, что и ваш шлюз иначе может ничего не работать. Теперь можете активировать подключение:
nmcli connection up static
7. Настройка Wifi
В графическом интерфейсе это делается одной галочкой, здесь одной командой. Смотрим состояние wifi:
nmcli radio wifi
nmcli radio wifi on
nmcli radio wifi off
Такой командой можно посмотреть список доступных сетей wifi:
nmcli device wifi list
Команда для подключения к новой сети wifi выглядит не намного сложнее. Например, давайте подключимся к сети TP-Link с паролем 12345678:
nmcli device wifi connect «TP-Link» password 12345678 name «TP-Link Wifi»
Если всё прошло хорошо, то вы получите уже привычное сообщение про создание подключения с именем TP-Link Wifi и это имя в дальнейшем можно использовать для редактирования этого подключения и управления им, как описано выше.
Выводы
Как видите, все очень просто и быстро. Настройка network manager в консоли выполняется в пару команд, достаточно только их запомнить или где-нибудь написать, чтобы вы могли выполнить управление сетью nmcli когда это понадобится.
Источник