NetworkManager (简体中文)

From ArchWiki
(Redirected from 网络管理器)

Tango-preferences-desktop-locale.png本文或本节需要翻译。要贡献翻译,请访问简体中文翻译团队Tango-preferences-desktop-locale.png

附注: Note Some English sections need update/fix before translation.(在 Talk:NetworkManager (简体中文)# 中讨论)
翻译状态:本文是 NetworkManager翻译。上次翻译日期:2022-11-17。如果英文版本有所更改,则您可以帮助同步翻译。

NetworkManager 是一个为系统提供检测和配置功能以便自动连接到网络的程序。NetworkManager 的功能对无线和有线网络都很有用。对于无线网络,NetworkManager 偏好已知的无线网络,并能切换到最可靠的网络。能感知 NetworkManager 的应用程序可以切换在线和离线模式。比起无线连接,NetworkManager 更偏好有线连接,且支持调制解调器连接和一些类型的 VPN。NetworkManager 最初由 Red Hat 开发,现在由 GNOME 管理。

警告: 默认情况下,文件系统中的 root 用户和通过 GUI(如 nm-applet)访问设置的用户可以访问机密信息(如 WiFi 密码)。参见#加密的 Wi-Fi 密码

安装

NetworkManager 可以通过 networkmanager 软件包安装。此软件包包含一个守护程序、一个命令行界面(nmcli)和一个基于 curses 的界面(nmtui)。

启用 NetworkManager

安装完成后,启动/启用 NetworkManager.service。NetworkManager 守护进程启动后,会自动连接到已配置且可用的“系统连接”。“用户连接”和未配置的连接需要通过 nmcli 或 applet 进行配置和连接。

注意:
  • 请确保没运行其它网络配置服务;多个网络服务会发生冲突。可以用 systemctl --type=service 查看正在运行的服务列表,然后停止它们。参见#配置以启用 NetworkManager 服务。
  • 如果 systemd-resolved 没有启动,错误消息将会淹没日志。详见后面的 Unit dbus-org.freedesktop.resolve1.service not found 部分。

额外的界面

移动网络支持

NetworkManager 使用 ModemManager 提供移动宽带连接。

安装 modemmanagerusb_modeswitch。然后启用启动 ModemManager.service

可能需要重新启动 NetworkManager.service 才能使其检测 ModemManager。重新启动后,重新插入调制解调器应该就可以识别了。

从前端界面(例如 nm-connection-editor)添加连接并将连接类型选择为 broadband,选择 ISP 和套餐, mobile-broadband-provider-info 会自动填入 APN 和其它设置。

PPPoE / DSL 支持

安装 rp-pppoe 以支持 PPPoE / DSL 连接。使用 nm-connection-editor 添加一个新的 DSL/PPPoE 连接。

VPN 支持

从 1.16 版本开始 NetworkManager 原生支持 WireGuard,它只需要 wireguard 内核模块。详见 WireGuard in NetworkManager 博客文章

对其他类型 VPN 的支持基于一个插件系统。它们在以下软件包中提供:

警告: 有很多与 VPN 支持有关的错误。Check the daemon processes options set via the GUI correctly and double-check with each package release.
注意: 要在使用 VPN 时获得完整的 DNS 解析,请设置条件转发

使用

NetworkManager 附带 nmcli(1)nmtui(1)

nmcli 示例

显示附近的 Wi-Fi 网络:

$ nmcli device wifi list

连接到 Wi-Fi 网络:

$ nmcli device wifi connect SSID_或_BSSID password 密码

连接到隐藏的 Wi-Fi 网络:

$ nmcli device wifi connect SSID_或_BSSID password 密码 hidden yes

连接到 wlan1 网络接口上的 Wi-Fi:

$ nmcli device wifi connect SSID_或_BSSID password 密码 ifname wlan1 profile_name

断开网络接口上的连接:

$ nmcli device disconnect ifname eth0

显示连接列表及其名称、UUID、类型和支持设备:

$ nmcli connection show

激活连接(即使用现有配置文件连接到网络):

$ nmcli connection up name_或_uuid

删除连接:

$ nmcli connection delete name_或_uuid

显示所有网络设备及其状态:

$ nmcli device

关闭 Wi-Fi:

$ nmcli radio wifi off

编辑连接

设置的完整列表参见 nm-settings(5)

首先需要获取连接列表:

$ nmcli connection
NAME                UUID                                  TYPE      DEVICE
Wired connection 2  e7054040-a421-3bef-965d-bb7d60b7cecf  ethernet  enp5s0
Wired connection 1  997f2782-f0fc-301d-bfba-15421a2735d8  ethernet  enp0s25
MY-HOME-WIFI-5G     92a0f7b3-2eba-49ab-a899-24d83978f308  wifi       --

第一列可以作为连接 connection-id, 本示例中使用 Wired connection 2

创建后有三种方法可以配置 Wired connection 2

nmcli 交互式编辑器
nmcli connection edit 'Wired connection 2'.
Usage is well documented from the editor.
nmcli 命令行界面
nmcli connection modify 'Wired connection 2' setting.property value. See nmcli(1) for usage. For example you can change its IPv4 route metric to 200 using nmcli connection modify 'Wired connection 2' ipv4.route-metric 200 command.

To remove a setting pass an empty field ("") to it like this:

nmcli connection modify 'Wired connection 2' setting.property ""
连接文件
/etc/NetworkManager/system-connections/ 中修改对应的 Wired connection 2.nmconnection 文件。
别忘了使用 nmcli connection reload 重新加载配置文件。

前端

为了配置和轻松使用 NetworkManager,大多数用户会希望安装一个 applet。这种图形前端往往显示在系统托盘(或通知区域),从而允许用户选择网络或者配置 NetworkManager。各种桌面环境都有自己的 applet。你也可以使用 #nm-applet

GNOME

GNOME网络设置 里有内置的配置工具。

KDE Plasma

安装 plasma-nm 软件包。然后通过 面板的选项 > 添加部件 > 网络 将其添加到 KDE 的任务栏上。

nm-applet

network-manager-applet 是一个工作在 Xorg 环境下的 GTK 3 前端,带有一个系统托盘。

为了存储连接密码,请安装并配置 GNOME Keyring

请注意,如果对某个连接启用了 对其他用户可用 选项,NetworkManager 就会明文存储密码,不过相应的文件只能被 root 或者其他使用 nm-applet 的用户访问。参照 #加密的 Wi-Fi 密码

要在没有系统托盘的情况下运行 nm-applet,可以使用 trayerstalonetray。例如,可以在自己的可执行文件路径中添加这样的脚本:

nmgui
#!/bin/sh
nm-applet    2>&1 > /dev/null &
stalonetray  2>&1 > /dev/null
killall nm-applet

当关闭 stalonetray 窗口的时候,它也会关闭 nm-applet,所以当你完成网络配置后它就不会再占用内存。

applet 可以显示一些事件的通知,比如连接或断开 WiFi。要显示这些消息,确保你已安装了一个通知服务器——请参见 Desktop notifications。如果在没有通知服务器的情况下使用,那么可能会在 stdout/stderr 中看到一些消息,并且 applet可能会挂起。请参见[1]

要在禁用通知的情况下使用 nm-applet,请使用以下命令运行 applet:

$ nm-applet --no-agent
提示: nm-applet 可能被自启动桌面配置项自动启动, 这种情况下请在那里的 Exec 一行添加 --no-agent 选项:
Exec=nm-applet --no-agent

Appindicator

从 1.18.0 版本开始,官方软件包 network-manager-applet包含 Appindicator 支持。要在 Appindicator 环境中使用 nm-applet,请使用以下命令启动 applet:

$ nm-applet --indicator

networkmanager-dmenu

networkmanager-dmenu-gitAUR 是一个通过 dmenurofi 而不是 nm-applet 管理 NetworkManager 连接的小脚本。它提供了所有必要的功能, 例如连接到已有的 NetworkManager wifi 或有线网络、连接到新的 wifi 网络、在需要的时候询问密码、连接到已有的 VPN、启用/停用网络连接、运行 nm-connection-editor 图形界面、连接到蓝牙网络等等。

配置

NetworkManager 需要一些额外的步骤才能正常运行。请确保已按照网络配置#设置计算机名一节的描述配置 /etc/hosts

NetworkManager 的全局配置文件位于 /etc/NetworkManager/NetworkManager.conf。额外的配置文件可以放在 /etc/NetworkManager/conf.d/ 中。全局的默认配置通常不需要改动。

编辑配置文件后,可以使用以下命令应用更改:

# nmcli general reload

NetworkManager-wait-online

Enabling NetworkManager.service also enables NetworkManager-wait-online.service, which is a oneshot system service that waits for the network to be configured. The latter has WantedBy=network-online.target, so it will finish only when network-online.target itself is enabled or pulled in by some other unit. See also systemd#Running services after the network is up.

By default, NetworkManager-wait-online.service waits for NetworkManager startup to complete, rather than waiting for network connectivity specifically (see nm-online(1)). If NetworkManager-wait-online.service finishes before the network is really up, resulting in failed services on boot, extend the unit to remove the -s from the ExecStart line:

[Service]
ExecStart=
ExecStart=/usr/bin/nm-online -q

注意这可能会导致其他问题

在某些情况下,由于超时太短,服务仍然无法在启动时成功启动。编辑服务,将 NM_ONLINE_TIMEOUT60 改为更大的值。

设置 PolicyKit 权限

默认情况下,活动的本地会话中的所有用户都能在没有密码的情况下改变大多数网络设置。参照 General troubleshooting (简体中文)#会话权限检查会话类型。在大多数情况下,一切都应该开箱即用。

一些操作(例如改变系统计算机名)需要管理员密码。这时,需要将自己添加wheel 用户组并运行一个 polkit 身份认证组件,它将提示输入密码。

对于远程会话(例如 headless VNC),有几种方法获得使用 NetworkManager 所需的权限:

  1. 将自己添加wheel 用户组。执行每个操作时都需要输入自己的密码。注意你的账户同时被赋予了此账户组的其他权限,例如使用 sudo 命令时无需输入 root 密码。
  2. 将自己添加network 用户组,同时创建一个包含以下内容的 /etc/polkit-1/rules.d/50-org.freedesktop.NetworkManager.rules 文件:
    polkit.addRule(function(action, subject) {
      if (action.id.indexOf("org.freedesktop.NetworkManager.") == 0 && subject.isInGroup("network")) {
        return polkit.Result.YES;
      }
    });
    
    network 用户组中的所有用户都将能免密码管理网络,这意味着不需要运行 polkit 身份认证组件,因此在 SSH 会话中也能工作。

代理设置

NetworkManager 不直接处理代理设置,但如果你使用 GNOMEKDE,你可以使用 proxydriverAUR,它将使用 NetworkManager 的信息处理代理设置。

要让 proxydriver 能够改变代理设置,you would need to execute this command, as part of the GNOME startup process (参见 GNOME (简体中文)#自启动)。

$ xhost +si:localuser:username

参见 Proxy server (简体中文)

Checking connectivity

NetworkManager can try to reach a webserver after connecting to a network in order to determine if it is e.g behind a captive portal. 默认主机(在 /usr/lib/NetworkManager/conf.d/20-connectivity.conf 中配置)是 ping.archlinux.org。To use a different webserver or to disable connectivity checking, create /etc/NetworkManager/conf.d/20-connectivity.conf, see NetworkManager.conf(5) § CONNECTIVITY SECTION. Below is an example of using GNOME servers (it does not require the use of GNOME):

/etc/NetworkManager/conf.d/20-connectivity.conf
[connectivity]
uri=http://nmcheck.gnome.org/check_network_status.txt

To disable NetworkManager's connectivity check, use the following configuration. This can be useful when connected to a VPN that blocks connectivity checks.

/etc/NetworkManager/conf.d/20-connectivity.conf
[connectivity] 
enabled=false
注意: Although automatic connectivity checks are a potential privacy leak, Arch Linux's default connectivity URL is committed to not logging any access. See [2] [3].

Captive portals

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements. See Help:Style for reference.Tango-edit-clear.png

Reason: Complex scripts should not be maintained on the wiki. (Discuss in Talk:NetworkManager (简体中文))

For those behind a captive portal, the desktop manager may automatically open a window asking for credentials. If your desktop does not, you can use capnet-assist package (however, it currently it has a broken NetworkManager dispatcher script). Alternatively, you can create a NetworkManager dispatcher script with the following content:

/etc/NetworkManager/dispatcher.d/90-open_captive_portal
#!/bin/sh -e
# Script to dispatch NetworkManager events
#
# Runs shows a login webpage on walled garden networks.
# See NetworkManager(8) for further documentation of the dispatcher events.

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

if [ -x "/usr/bin/logger" ]; then
    logger="/usr/bin/logger -s -t captive-portal"
else
    logger=":"
fi

wait_for_process() {
    PNAME=$1
    while [ -z "$(/usr/bin/pgrep $PNAME)" ]; do
        sleep 3;
    done
}

#launch the browser, but on boot we need to wait that nm-applet starts
start_browser() {
    local user="$1"
    local display="$2"

    export DISPLAY="$display"
    wait_for_process nm-applet

    export XAUTHORITY="/home/$user/.Xauthority"

    $logger "Running browser as '$user' with display '$display' to login in captive portal"
    sudo -u "$user" --preserve-env=DISPLAY,XAUTHORITY -H xdg-open http://capnet.elementary.io 2>&1 > /dev/null
}

# Run the right scripts
case "$2" in
    connectivity-change)
    $logger -p user.debug "dispatcher script triggered on connectivity change: $CONNECTIVITY_STATE"
    if [ "$CONNECTIVITY_STATE" = "PORTAL" ]; then
        # Match last column of who's output with ' :[at least one digit] '
        who | awk '$NF ~ /\(:[0-9]+\)/ { print $1 " " substr($NF, 2, length($NF)-2) };' | \
        while read user display; do
            start_browser $user $display || $logger -p user.err "Failed for user: '$user' display: '$display'"
        done
    fi
    ;;
    *)
    # In a down phase
    exit 0
    ;;
esac

You will need to restart NetworkManager.service or reboot for this to start working. Once you do, the dispatcher script should open a login window once it detects you are behind a captive portal.

Another solution is captive-browser-gitAUR based on Google Chrome.

DHCP 客户端

NetworkManager 默认使用内置的 DHCP 客户端。内置的 DHCPv4 插件基于 nettools 的 n-dhcp4 库,而内置的 DHCPv6 插件的代码基于 systemd-networkd。

要使用不同的 DHCP 客户端,安装以下之一:

要更改 DHCP 客户端后端,请在 /etc/NetworkManager/conf.d/ 中的配置文件中设置选项 main.dhcp=dhcp 客户端名称。例如:

/etc/NetworkManager/conf.d/dhcp-client.conf
[main]
dhcp=dhclient
注意:
  • NetworkManger does not support using dhcpcd for IPv6. See NetworkManager issue #5.如果将 dhcpcd 设置为 DHCP 客户端,NetworkManager 将为 DHCPv6 使用内置 DHCP 客户端。
  • 不要启用 dhclientdhcpcd 软件包提供的 systemd 单元。它们会与 NetworkManager 冲突,详情请参见#安装中的注释。

DNS 管理

NetworkManager 的 DNS 管理在 GNOME 项目的 wiki 页面中进行了描述——Projects/NetworkManager/DNS

DNS 缓存和条件转发

NetworkManager has a plugin to enable DNS caching and conditional forwarding (previously called "split DNS" in NetworkManager's documentation) using dnsmasq or systemd-resolved. The advantages of this setup is that DNS lookups will be cached, shortening resolve times, and DNS lookups of VPN hosts will be routed to the relevant VPN's DNS servers. This is especially useful if you are connected to more than one VPN.

Note: If /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, NetworkManager will choose systemd-resolved automatically. To use dnsmasq, you must first remove that symlink, then restart NetworkManager.
dnsmasq

确保已安装 dnsmasq。然后在 /etc/NetworkManager/conf.d/ 中的配置文件中设置 main.dns=dnsmasq

/etc/NetworkManager/conf.d/dns.conf
[main]
dns=dnsmasq

现在以 root 身份运行 nmcli general reload。NetworkManager 将自动启动 dnsmasq 并将 127.0.0.1 添加到 /etc/resolv.conf。原来的 DNS 服务器可以在 /run/NetworkManager/no-stub-resolv.conf 中找到。You can verify dnsmasq is being used by doing the same DNS lookup twice with drill example.com and verifying the server and query times.

注意:
  • 无需启动 dnsmasq.service 或编辑 /etc/dnsmasq.conf。NetworkManager 不通过 systemd 服务启动 dnsmasq,也不会读取 dnsmasq 的默认配置文件。
  • The dnsmasq instance started by NetworkManager will bind to 127.0.0.1:53, you cannot run any other software (including dnsmasq.service) on the same address and port.
自定义 dnsmasq 配置

可以通过在 /etc/NetworkManager/dnsmasq.d/ 中创建配置文件为 dnsmasq 创建自定义配置。例如,要更改 DNS 缓存(存储在 RAM 中)的大小:

/etc/NetworkManager/dnsmasq.d/cache.conf
cache-size=1000

可以使用以下命令检查配置文件语法:

$ dnsmasq --test --conf-file=/dev/null --conf-dir=/etc/NetworkManager/dnsmasq.d

所有可用选项请参见 dnsmasq(8)

IPv6

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: This does not solve the issue because NetworkManager does not add ::1 to /etc/resolv.conf. Unless @::1 is manually passed to drill, it will still fail with Error: error sending query: No (valid) nameservers defined in the resolver. (Discuss in Talk:NetworkManager (简体中文))

Enabling dnsmasq in NetworkManager may break IPv6-only DNS lookups (i.e. drill -6 [hostname]) which would otherwise work. In order to resolve this, creating the following file will configure dnsmasq to also listen to the IPv6 loopback:

/etc/NetworkManager/dnsmasq.d/ipv6-listen.conf
listen-address=::1

In addition, dnsmasq also does not prioritize upstream IPv6 DNS. Unfortunately NetworkManager does not do this (Ubuntu Bug). A workaround would be to disable IPv4 DNS in the NetworkManager config, assuming one exists.

DNSSEC

The dnsmasq instance started by NetworkManager by default will not validate DNSSEC since it is started with the --proxy-dnssec option. It will trust whatever DNSSEC information it gets from the upstream DNS server.

For dnsmasq to properly validate DNSSEC, thus breaking DNS resolution with name servers that do not support it, create the following configuration file:

/etc/NetworkManager/dnsmasq.d/dnssec.conf
conf-file=/usr/share/dnsmasq/trust-anchors.conf
dnssec
systemd-resolved

NetworkManager 能以 systemd-resolved 作为DNS解析器和缓存。在使用其之前,确保你已正确配置 systemd-resolved 并且 systemd-resolved.service 已经启动

如果 /etc/resolv.conf 是一个指向 /run/systemd/resolve/stub-resolv.conf/run/systemd/resolve/resolv.conf/usr/lib/systemd/resolv.conf符号链接,systemd-resolved会自动启用。

你也可以通过编写 /etc/NetworkManager/conf.d/ 下的配置文件,设置 main.dns=systemd-resolved 来显式启用它:

/etc/NetworkManager/conf.d/dns.conf
[main]
dns=systemd-resolved
DNS resolver with an openresolv subscriber

If openresolv has a subscriber for your local DNS resolver, set up the subscriber and configure NetworkManager to use openresolv.

Because NetworkManager advertises a single "interface" to resolvconf, it is not possible to implement conditional forwarding between two NetworkManager connections. See NetworkManager issue 153.

This can be partially mitigated if you set private_interfaces="*" in /etc/resolvconf.conf[4]. Any queries for domains that are not in search domain list will not get forwarded. They will be handled according to the local resolver's configuration, for example, forwarded to another DNS server or resolved recursively from the DNS root.

自定义 DNS 服务器

设置自定义全局 DNS 服务器

To set DNS servers for all connections, specify them in NetworkManager.conf(5) using the syntax servers=serveripaddress1,serveripaddress2,serveripaddress3 in a section named [global-dns-domain-*]. For example:

/etc/NetworkManager/conf.d/dns-servers.conf
[global-dns-domain-*]
servers=::1,127.0.0.1
注意:
设置自定义连接 DNS 服务器
设置自定义连接 DNS 服务器(GUI)

Setup will depend on the type of front-end used; the process usually involves right-clicking on the applet, editing (or creating) a profile, and then choosing DHCP type as Automatic (specify addresses). The DNS addresses will need to be entered and are usually in this form: 127.0.0.1, DNS-server-one, ....

设置自定义连接 DNS 服务器(nmcli / 连接文件)

To setup DNS Servers per connection, you can use the dns field (and the associated dns-search and dns-options) in the connection settings[损坏的链接:无效的章节].

If method is set to auto (when you use DHCP), you need to set ignore-auto-dns to yes.

/etc/resolv.conf

NetworkManager's /etc/resolv.conf management mode is configured with the main.rc-manager setting. networkmanager sets it to symlink as apposed to the upstream default auto. The setting and its values are documented in the NetworkManager.conf(5) man page.

Tip: Using openresolv allows NetworkManager to coexists with other resolvconf supporting software or, for example, to run a local DNS caching and split-DNS resolver for which openresolv has a subscriber. Note that conditional forwarding is not yet fully supported when using NetworkManager with openresolv.

NetworkManager also offers hooks via so called dispatcher scripts that can be used to alter the /etc/resolv.conf after network changes. See #Network services with NetworkManager dispatcher[损坏的链接:无效的章节] and NetworkManager(8) for more information.

Note:
  • If NetworkManager is configured to use either dnsmasq or systemd-resolved, then the appropriate loopback addresses will be written to /etc/resolv.conf.
  • The resolv.conf file NetworkManager writes or would write to /etc/resolv.conf can be found at /run/NetworkManager/resolv.conf.
  • A resolv.conf file with the acquired name servers and search domains can be found at /run/NetworkManager/no-stub-resolv.conf.
Unmanaged /etc/resolv.conf

To stop NetworkManager from touching /etc/resolv.conf, set main.dns=none with a configuration file in /etc/NetworkManager/conf.d/:

/etc/NetworkManager/conf.d/dns.conf
[main]
dns=none
Tip: You might also want to set main.systemd-resolved=false, so that NetworkManager does not send the DNS configuration to systemd-resolved.
Note: See DNS caching and conditional forwarding, to configure NetworkManager using other DNS backends like dnsmasq and systemd-resolved, instead of using main.dns=none.

After that /etc/resolv.conf might be a broken symlink that you will need to remove. Then, just create a new /etc/resolv.conf file.

Use openresolv
Note: NetworkManager does not support using systemd-resolved's resolvconf interface (resolvectl(1) § COMPATIBILITY WITH RESOLVCONF(8)) which is provided by systemd-resolvconf.

To configure NetworkManager to use openresolv, set main.rc-manager=resolvconf with a configuration file in /etc/NetworkManager/conf.d/:

/etc/NetworkManager/conf.d/rc-manager.conf
[main]
rc-manager=resolvconf

防火墙

可以根据当前的连接分配 firewalld 区域。例如,在工作时限制较多,在家时限制较少。

也可以通过 NetworkManager 调度实现。

使用 NetworkManager 调度网络服务

有些服务只有联网时才有意义,例如 NFS, SMBNTPd。NetworkManager 可以在连接网络后启动这些服务,并在网络关闭时停止它们。

要使用这一功能, 需要 enablestart NetworkManager-dispatcher.service

服务启动后,可以将脚本加到 /etc/NetworkManager/dispatcher.d 目录。

这些脚本必须属于 root, 否则不会被执行。为了安全起见, 所属 用户组也设置为 root:

# chown root:root /etc/NetworkManager/dispatcher.d/10-script.sh

而且脚本必须是 可执行

# chmod 755 scriptname

脚本将在连接网络时按字母表顺序运行,并在网络停止时反向停止。要保证启动顺序,可以在前面加数字,例如 10_portmap30_netfs 这样就能保证 portmapper 在 NFS 挂载之前启动。

脚本将接收如下参数:

  • Interface name: 例如 eth0
  • Action: up, down, vpn-up, vpn-down, ... (完整列表请参考 NetworkManager(8))
警告: 如果没有连接到外部网络,请注意启动的服务和需要它们的程序。如果连接公共网络时启动了错误的服务,可能导致安全问题。

避免超时

如果一切运行良好, 那么这一节就可以跳过了。 However, there is a general problem related to running dispatcher scripts which take longer to be executed. Initially an internal timeout of three seconds only was used. If the called script did not complete in time, it was killed. Later the timeout was extended to about 20 seconds (see the Bugtracker for more information). If the timeout still creates the problem, a work around may be to modify the dispatcher service file /usr/lib/systemd/system/NetworkManager-dispatcher.service to remain active after exit:

/etc/systemd/system/NetworkManager-dispatcher.service
.include /usr/lib/systemd/system/NetworkManager-dispatcher.service
[Service]
RemainAfterExit=yes

运行修改后的 NetworkManager-dispatcher 服务并将其设置为开机启动。

警告: 加入了 RemainAfterExit 那一行后会让 dispatcher 一直运行。不幸的是, dispatcher 必须在再次运行脚本前被关闭。这意味着脚本只能被运行一次。因此, 除非超时确实引起了问题, 否则不要修改服务文件。

Dispatcher examples

Mount remote directory with sshfs

由于该脚本在一个非常受限制的环境中运行, 为了连接上SSH agent, 你必须 export SSH_AUTH_SOCK。 这里有几种不同方式, 参照 here 获取更多详细信息. 以下示例需要 gnome-keyring , 如果 gnome-keyring 没解锁,将需要你输入密码. 如果 NetworkManager 设置为登录后自动连接, 很有可能因为 gnome-keyring 还没启动导致失败(转入睡眠). 对应的 UUID 可以通过命令 nmcli con statusnmcli con list 查得。

#!/bin/sh
USER='username'
REMOTE='user@host:/remote/path'
LOCAL='/local/path'

interface=$1 status=$2
if [ "$CONNECTION_UUID" = "uuid" ]; then
  case $status in
    up)
      # sleep 10
      SSH_AUTH_SOCK=$(find /tmp -maxdepth 1 -type s -user "$USER" -name 'ssh')
      export SSH_AUTH_SOCK
      su "$USER" -c "sshfs $REMOTE $LOCAL"
      ;;
    down)
      fusermount -u "$LOCAL"
      ;;
  esac
fi

Mounting of SMB shares

Some SMB shares are only available on certain networks or locations (e.g. at home). You can use the dispatcher to only mount SMB shares that are present at your current location.

The following script will check if we connected to a specific network and mount shares accordingly:

/etc/NetworkManager/dispatcher.d/30-mount-smb.sh
#!/bin/sh

# Find the connection UUID with "nmcli connection show" in terminal.
# All NetworkManager connection types are supported: wireless, VPN, wired...
if [ "$2" = "up" ]; then
  if [ "$CONNECTION_UUID" = "uuid" ]; then
    mount /your/mount/point & 
    # add more shares as needed
  fi
fi

The following script will unmount all SMB shares before a software initiated disconnect from a specific network:

/etc/NetworkManager/dispatcher.d/pre-down.d/30-umount-smb.sh
#!/bin/sh

if [ "$CONNECTION_UUID" = "uuid" ]; then
  umount -a -l -t cifs
fi
Note: Make sure this script is located in the pre-down.d sub-directory as shown above, otherwise it will unmount all shares on any connection state change.

The following script will attempt to unmount all SMB shares following an unexpected disconnect from a specific network:

/etc/NetworkManager/dispatcher.d/40-umount-smb.sh
#!/bin/sh

if [ "$CONNECTION_UUID" = "uuid" ]; then
  if [ "$2" = "down" ]; then
    umount -a -l -t cifs
  fi
fi
Note:
  • Since NetworkManager 0.9.8, the pre-down and down events are not executed on shutdown or restart, see this bug report for more info.
  • The previous umount scripts are still prone to leaving applications actually accessing the mount to 'hang'.

An alternative is to use the script as seen in NFS#Using a NetworkManager dispatcher:

/etc/NetworkManager/dispatcher.d/30-smb.sh
#!/bin/sh

# Find the connection UUID with "nmcli con show" in terminal.
# All NetworkManager connection types are supported: wireless, VPN, wired...
WANTED_CON_UUID="CHANGE-ME-NOW-9c7eff15-010a-4b1c-a786-9b4efa218ba9"

if [ "$CONNECTION_UUID" = "$WANTED_CON_UUID" ]; then
    
    # Script parameter $1: network interface name, not used
    # Script parameter $2: dispatched event
    
    case "$2" in
        "up")
            mount -a -t cifs
            ;;
        "down"|"pre-down"|"vpn-pre-down")
            umount -l -a -t cifs >/dev/null
            ;;
    esac
fi
Note: This script ignores mounts with the noauto option, remove this mount option or use auto to allow the dispatcher to manage these mounts.

Create a symlink inside /etc/NetworkManager/dispatcher.d/pre-down/ to catch the pre-down events:

# ln -s ../30-smb.sh /etc/NetworkManager/dispatcher.d/pre-down.d/30-smb.sh

Mounting of NFS shares

See NFS#Using a NetworkManager dispatcher.

Use dispatcher to automatically toggle wireless depending on LAN cable being plugged in

The idea is to only turn Wi-Fi on when the LAN cable is unplugged (for example when detaching from a laptop dock), and for Wi-Fi to be automatically disabled, once a LAN cable is plugged in again.

Create the following dispatcher script[5], replacing LAN_interface with yours.

Note that there is a fail-safe for the case when the LAN interface was connected when the computer was last on, and then disconnected while the computer was off. That would mean the radio would still be off when the computer is turned back on, and with a disconnected LAN interface, you would have no network.

/etc/NetworkManager/dispatcher.d/wlan_auto_toggle.sh
#!/bin/sh

if [ "$1" = "LAN_interface" ]; then
    case "$2" in
        up)
            nmcli radio wifi off
            ;;
        down)
            nmcli radio wifi on
            ;;
    esac
elif [ "$(nmcli -g GENERAL.STATE device show LAN_interface)" = "20 (unavailable)" ]; then
    nmcli radio wifi on
fi
Note: You can get a list of interfaces using nmcli. The Ethernet (LAN) interfaces start with en, e.g. enp0s5

使用 dispatcher 在网络连接建立后连接 vpn

此部分示例演示如果自动连接到NetworkManager已定义的vpn-connection.首先创建调度脚本定义vpn连接之后的事务

Note: 要使用 iwgetid,需要安装 wireless_tools
/etc/NetworkManager/dispatcher.d/vpn-up
#!/bin/sh
VPN_NAME="name of VPN connection defined in NetworkManager"
ESSID="Wi-Fi network ESSID (not connection name)"

interface=$1 status=$2
case $status in
  up|vpn-down)
    if iwgetid | grep -qs ":\"$ESSID\""; then
      nmcli connection up id "$VPN_NAME"
    fi
    ;;
  down)
    if iwgetid | grep -qs ":\"$ESSID\""; then
      if nmcli connection show --active | grep "$VPN_NAME"; then
        nmcli connection down id "$VPN_NAME"
      fi
    fi
    ;;
esac

如果想在任意 Wi-Fi 网络都可以自动连接 VPN, 你可以用这样给 ESSID 赋值: ESSID=$(iwgetid -r)。记住要给脚本设置相应的权限, 参见 上文

由于 VPN secrets 保管方式的原因, 连接依然可能会失败并且 NetworkManager-dispatcher.service 会报错 'no valid VPN secrets'。这样就需要用下面方法让脚本可以获取 VPN 密码:

或者直接在 VPN 配置文件中加入 vpn-secrets 并写入密码:

1: 可以选择编辑 VPN 连接的配置文件让 NetworkManager 自己储存 secrets 而不是把 secrets 保存在 不能被root访问的 keyring 中: 打开 /etc/NetworkManager/system-connections/name of your VPN connection, 把 password-flags 以及 secret-flags1 改为 0

如果还不行,需要在安全位置创建 passwd-file,权限和 dispatcher 脚本一致,并添加如下内容:

/path/to/passwd-file
vpn.secrets.password:YOUR_PASSWORD

脚本也需要做出相应修改:

/etc/NetworkManager/dispatcher.d/vpn-up
#!/bin/sh
VPN_NAME="name of VPN connection defined in NetworkManager"
ESSID="Wi-Fi network ESSID (not connection name)"

interface=$1 status=$2
case $status in
  up|vpn-down)
    if iwgetid | grep -qs ":\"$ESSID\""; then
      nmcli connection up id "$VPN_NAME" passwd-file /path/to/passwd-file
    fi
    ;;
  down)
    if iwgetid | grep -qs ":\"$ESSID\""; then
      if nmcli connection show --active | grep "$VPN_NAME"; then
        nmcli connection down id "$VPN_NAME"
      fi
    fi
    ;;
esac

2: 修改 password-flags,将密码加入配置文件的 vpn-secrets 部分:

 [vpn]
 ....
 password-flags=0
 
 [vpn-secrets]
 password=your_password
Note: 可能需要打开配置界面,重新设置 VPN 密码。

Use dispatcher to disable IPv6 on VPN provider connections

Many commercial VPN providers support only IPv4. That means all IPv6 traffic bypasses the VPN and renders it virtually useless. To avoid this, dispatcher can be used to disable all IPv6 traffic for the time a VPN connection is up.

/etc/NetworkManager/dispatcher.d/10-vpn-ipv6
#!/bin/sh

case "$2" in
	vpn-up)
		echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6
		;;
	vpn-down)
		echo 0 > /proc/sys/net/ipv6/conf/all/disable_ipv6
		;;
esac

启动 OpenNTPD

安装 networkmanager-dispatcher-openntpdAUR 软件包

Dynamically set NTP servers received via DHCP with systemd-timesyncd

When roaming between different networks (e.g. a company's LAN, WiFi at home, various other WiFi now and then) you might want to set the NTP server(s) used by timesyncd to those provided by DHCP. However, NetworkManager itself is not capable to communicate with systemd-timesyncd to set the NTP server(s).

The dispatcher can work around it.

Create the overlay directory for your systemd-timesyncd configuration /etc/systemd/timesyncd.conf.d if it does not already exist. Inside /etc/NetworkManager/dispatcher.d, put the following:

/etc/NetworkManager/dispatcher.d/10-update-timesyncd
#!/bin/sh

[ -z "$CONNECTION_UUID" ] && exit 0
INTERFACE="$1"
ACTION="$2"

case $ACTION in
up | dhcp4-change | dhcp6-change)
    [ -n "$DHCP4_NTP_SERVERS" ] || exit
    mkdir -p /etc/systemd/timesyncd.conf.d
    cat <<-THE_END >"/etc/systemd/timesyncd.conf.d/${CONNECTION_UUID}.conf"
        [Time]
        NTP=$DHCP4_NTP_SERVERS
    THE_END
    systemctl restart systemd-timesyncd.service
    ;;
down)
    rm -f "/etc/systemd/timesyncd.conf.d/${CONNECTION_UUID}.conf"
    systemctl restart systemd-timesyncd.service
    ;;
esac

Every time NetworkManager sets up a new network connection (ACTION=up) or gets some update for an existing connection (ACTION=dhcp4-change or ACTION=dhcp6-change) and the provided connection data contains information about NTP server(s) (DHCP4_NTP_SERVERS), a connection specific overlay configuration file is written to /etc/systemd/timesyncd.conf.d, containing the provided NTP server(s). Whenever a connection is taken down (ACTION=down) the connection specific overlay file is removed. After each change to the configuration of systemd-timesyncd, this service is restarted to pick up the updated configuration. The use of connection specific configuration files is intentional so that when two or more connections are managed by NetworkManager in parallel the different NTP server names in the configuration are not overwritten as up, dhcp4-change, dhcp6-change and down actions might come in in an arbitrary order.

测试

NetworkManager 托盘组件被设计成开机自动启动,所以对大部分用户来说,并不需要过多配置。但是如果你手动停用旧有的网络设置断网,你需要测试一下 NetworkManager 是否正常工作。首先启动 NetworkManager.service.

有些托盘组件会提供给你一个 .desktop 文件以便通过系统菜单运行。如果没有,那你就需要通过命令或者注销重登录系统来让托盘组件运行。 一旦托盘组件运行了,它会自动请求网络连接并通过 DHCP 服务器来进行网络配置。

在一些 non-xdg-compliant 窗口系统,比如在 awesome 中启动 GNOME applet:

nm-applet --sm-disable &

如果需要静态 IP,你需要配置 NetworkManager。一般来说,在托盘图标上面点击右键,选择「编辑连接」即可。

提示与技巧

加密的 Wi-Fi 密码

NetworkManager 默认会在 /etc/NetworkManager/system-connections/ 中的连接文件当中以明文形式存储密码。要显示存储的密码,使用以下命令:

# grep -r '^psk=' /etc/NetworkManager/system-connections/

密码可以被文件系统中的 root 用户和通过 GUI(如 nm-applet)访问设置的用户访问。

更好的做法是以加密形式将密码存储在钥匙环中而不是以明文形式存储。使用钥匙环的缺点是连接要为每一个用户设置。

使用 GNOME 钥匙环

需要启动钥匙环守护程序并解锁钥匙环才能让之后的东西工作。

Furthermore, NetworkManager needs to be configured not to store the password for all users. Using GNOME's network-manager-applet, run nm-connection-editor from a terminal, select a network connection, click Edit, select the Wi-Fi Security tab and click on the right icon of password and check Store the password only for this user.

使用 KDE Wallet

Using KDE's plasma-nm, click the applet, click on the top right Settings icon, click on a network connection, in the General configuration tab, untick All users may connect to this network. If the option is ticked, the passwords will still be stored in clear text, even if a keyring daemon is running.

If the option was selected previously and you un-tick it, you may have to use the reset option first to make the password disappear from the file. Alternatively, delete the connection first and set it up again.

通过Wi-Fi共享网络连接

使用nm,你只要点击几下就可以共享你的internet连接(例如,3G或者有线)。你需要一个支持的Wi-Fi卡(基于Atheros AR9xx或者至少AR5xx的网卡可能是最好的选择)。

安装dnsmasq 以实现连接共享。NetworkManager 会启动自己的 dnsmasq 实例,与 dnsmasq.service 独立。

  • 点击小程序,选择"Create new wireless network"。
  • 按照指南 (如果使用WEP, 确保使用5到13字符长度的密码,其他的长度可能会失败)。
  • 下次你需要的时候,设置依然在存储着。

The connection will be saved and remain stored for the next time you need it.

Note: Android 不支持 Ad-hoc 模式. 要与 Android 设备共享网络,需要使用 infrastructure mode (Wi-Fi 模式设置为 "Hotspot").

通过Ethernet共享连接

场景: 你的设备有通过wi-fi的internet连接,你想通过ethernet和其他设备共享internet连接。

要求:

  • 安装dnsmasq以能够真正地共享连接。
  • 你的连有internet的设备和其他的设备通过合适的ethernet线缆连接(通常这意味着一个交叉线(cross over cable)或者之间有一个交换机(switch))

步骤:

  • 从终端运行nm-connection-editor
  • 添加一个新的ethernet连接
  • 给它起一个合适的名字。比如"共享连接"
  • 转到"IPv4 设置"(IPv4 settings)
  • 对于"方法:"(method) 选择 "与其他电脑共享"(Shared to other computers)
  • 保存

现在,你在NetworkManager的有线连接下应该有了一个新"共享连接"的选项。

在cron任务(jobs)或脚本中检查网络是否连接

有些cron任务需要可用的网络连接才能成功。你可能希望在网络不可用时避免运行这些任务。为此,添加一个网络的if 测试,该测试询问NetworkManager的nm-tool 并检查网状态。下面展示的测试当任何接口可用时成功,当所有借口都不可用时失败。对于可能连接有线,无线或者关闭网络的笔记本来说这很方便。

if [ $(nm-tool|grep State|cut -f2 -d' ') == "connected" ]; then
    #Whatever you want to do if the network is online
else
    #Whatever you want to do if the network is offline - note, this and the else above are optional
fi

例如,这对于一个运行fpupdate来更新F-Prot病毒扫描签名的cron.hourly脚本很有帮助。另外,经过小的修改,使用nm-tool输出的不同部分可以区分不同的网络;例如,因为活跃的无线网络连接有一个星号(asterisk'*')表示,你可以grep网络名,然后grep星号。

登陆后自动解锁秘钥环

NetworkManager 默认不会连接到需要密码的网络,仅在登录后才会连接,要不登录就连接网络,请使用下面方式配置:

  1. 右击面板中的nm-applet图标,并选择编辑连接(Edit Connections),打开无线(wireless)选项卡
  2. 选择你想要使用的连接并单击编辑
  3. 勾选"自动连接"(“Connect Automatically”)框和"对所有用户可用"(“Available to all users”)框

登出并重新登录,完成。

有密码认证的KDE and OpenConnect VPN

虽然可以在连接时直接输入,plasma-nm 0.9.3.2-1及以上版本还支持从 KWallet 中获取OpenConnect用户名和密码。

打开"KDE Wallet Manager"在"Network Management|Maps"下面查找你的OpenConnect VPN连接。点击"Show values"并在这个表的键值"VpnSecrets"下输入你的凭据(相应替代'username'和'password'):

form:main:username%SEP%username%SEP%form:main:password%SEP%password

下次你连接时,用户名和密码会出现在"VPN secrets"对话框中。

忽略特定设备

有时,可能希望Networkmanager忽略特定的设备,并且不为他们配置地址和路由。通过在/etc/NetworkManager/NetworkManager.conf中使用下述配置,你可以快速轻松地按照MAC或者接口名忽略设备。

[keyfile]
unmanaged-devices=mac:00:22:68:1c:59:b1;mac:00:1E:65:30:D1:C4;interface-name:eth0

填入上述内容后,执行 # nmcli general reload 后,应该能在NetworkManager不改变已完成设置的情况下配置接口。

Configuring MAC address randomization

Note: Disabling MAC address randomization may be needed to get (stable) link connection [6] and/or networks that restrict devices based on their MAC Address or have a limit network capacity.

MAC randomization can be used for increased privacy by not disclosing your real MAC address to the network.

NetworkManager supports two types MAC Address Randomization: randomization during scanning, and for network connections. Both modes can be configured by modifying /etc/NetworkManager/NetworkManager.conf or by creating a separate configuration file in /etc/NetworkManager/conf.d/ which is recommended since the aforementioned configuration file may be overwritten by NetworkManager.

Randomization during Wi-Fi scanning is enabled by default, but it may be disabled by adding the following lines to /etc/NetworkManager/NetworkManager.conf or a dedicated configuration file under /etc/NetworkManager/conf.d:

/etc/NetworkManager/conf.d/wifi_rand_mac.conf
[device]
wifi.scan-rand-mac-address=no

MAC randomization for network connections can be set to different modes for both wireless and ethernet interfaces. See the GNOME blog post for more details on the different modes.

In terms of MAC randomization the most important modes are stable and random. stable generates a random MAC address when you connect to a new network and associates the two permanently. This means that you will use the same MAC address every time you connect to that network. In contrast, random will generate a new MAC address every time you connect to a network, new or previously known. You can configure the MAC randomization by adding the desired configuration under /etc/NetworkManager/conf.d:

/etc/NetworkManager/conf.d/wifi_rand_mac.conf
[device-mac-randomization]
# "yes" is already the default for scanning
wifi.scan-rand-mac-address=yes
 
[connection-mac-randomization]
# Randomize MAC for every ethernet connection
ethernet.cloned-mac-address=random
# Generate a random MAC for each WiFi and associate the two permanently.
wifi.cloned-mac-address=stable

See the following GNOME blog post for more details.

启用IPv6隐私扩展

参见 IPv6#NetworkManager

Configure a unique DUID per connection

The DHCPv6 Unique Identifier (DUID) is a value used by the DHCPv6 client to identify itself to DHCPv6 servers. NetworkManager supports 3 types of DUID:

  • DUID-UUID (RFC 6355): generated from an Universally Unique IDentifier (UUID).
  • DUID-LL (RFC 3315): generated from the Link-Layer address (aka MAC address).
  • DUID-LLT (RFC 3315): generated from the Link-Layer address plus a timestamp.

If the internal NetworkManager's DHCP client is in use (the default) it will identify itself with a global and permanent DUID-UUID generated from the machine-id (/etc/machine-id). This means that all connections share the same UUID, which may be a privacy breach.

Fortunately, NetworkManager is able to provide unique DUIDs per connection, derived from the connection's stable-id and a per-host unique key. You can enable that by adding the following configuration under /etc/NetworkManager/conf.d:

/etc/NetworkManager/conf.d/duid.conf
[connection]
ipv6.dhcp-duid=stable-uuid

The stable-ll and stable-llt values are also supported. For further information read the description for dhcp-duid in nm-settings(5) § ipv6 setting.

Working with wired connections

By default, NetworkManager generates a connection profile for each wired ethernet connection it finds. At the point when generating the connection, it does not know whether there will be more Ethernet adapters available. Hence, it calls the first wired connection "Wired connection 1". You can avoid generating this connection, by configuring no-auto-default (see NetworkManager.conf(5)), or by simply deleting it. Then NetworkManager will remember not to generate a connection for this interface again.

You can also edit the connection (and persist it to disk) or delete it. NetworkManager will not re-generate a new connection. Then you can change the name to whatever you want. You can use something like nm-connection-editor for this task.

Using iwd as the Wi-Fi backend

Note:
  • Do not enable iwd.service or manually configure iwd. NetworkManager will start and manage it itself.
  • Consider existing issues before switching to iwd.

To enable the experimental iwd backend, first install iwd and then create the following configuration file:

/etc/NetworkManager/conf.d/wifi_backend.conf
[device]
wifi.backend=iwd

Alternatively, you can install networkmanager-iwdAUR, a modified package configured to build NetworkManager working exclusively with iwd, with the main difference being that iwd is required and wpa_supplicant can be uninstalled after building.

Note: You may need to convert existing NetworkManager network profiles after switching to iwd.

Running in a network namespace

If you would like to run NetworkManager inside a network namespace (e.g., to manage a specific device which should be use by selected applications), bring the device down before moving it to the namespace:

$ ip link set dev MY_DEVICE down
$ ip link set dev MY_DEVICE netns MY_NAMESPACE
$ ip netns exec MY_NAMESPACE NetworkManager
...
$ ip netns exec MY_NAMESPACE killall NetworkManager

otherwise NetworkManager will later fail to establish the connection with a device is strictly unmanaged error.

Automatically connect to VPN

NetworkManager can be set to automatically connect to a VPN when connecting to the internet, on a per network basis. The VPN connection itself can be added in GNOME's NetworkManager front-end, but to make it automatically use the VPN nmcli must be used. Other front-ends might not have this limitation.

First, make sure to make the VPN connection available to all users. In the GNOME this is a matter of checking a box under the details tab. Under the Identity tab, in the password field, click the icon on the right side in the field, and set it to Store the password for all users.

Then find the UUID of the VPN connection, and add that to connection.secondaries of the Internet connection:

# UUID=$(nmcli --get-values connection.uuid connection show name-of-VPN-connection)
# nmcli connection modify name-of-Internet-connection connection.secondaries "$UUID"

Now when NetworkManager is restarted and you connect to the Internet connection you have configured, you should automatically get connected to the VPN.

问题解决

安全 Wi-Fi 网络不提示输入密码

尝试连接到安全的 Wi-Fi 网络时,既不提示输入密码,也不建立连接。如果没有安装密钥环软件包,这种情况就会发生。一个简单的解决方案是安装 gnome-keyring。如果希望密码以加密的形式存储,按照 GNOME (简体中文)/Keyring (简体中文) 来设置 gnome-keyring-daemon

Network management disabled

当 NetworkManager 关闭但 pid(state)文件未删除时,就会看到 Network management disabled 提示。此时,请手动删除文件:

# rm /var/lib/NetworkManager/NetworkManager.state

内置 DHCP 客户端的问题

如果在使用内置 DHCP 客户端获取 IP 地址时遇到问题,请考虑换一个 DHCP 客户端,有关说明,请参阅 #DHCP 客户端。这种解决方法可能会解决大型无线网络(如 eduroam)中的问题。

使用 dhclient 时的 DHCP 问题

如果在通过 DHCP 获取 IP 地址时遇到问题,尝试在 /etc/dhclient.conf 中添加以下内容:

 interface "eth0" {
   send dhcp-client-identifier 01:aa:bb:cc:dd:ee:ff;
 }

其中 aa:bb:cc:dd:ee:ff 是网卡的 MAC 地址。MAC 地址可以使用 iproute2 包中的 ip link show 接口 命令获得。

未检测到 3G 调制解调器

参见 Mobile broadband modem#NetworkManager

在笔记本电脑上关闭 WLAN

有时候在使用笔记本上的开关禁用 Wi-Fi 然后重新启用后,NetworkManager 无法工作。这常常是 rfkill 的问题。要检查驱动程序是否已告知 rfkill 无线适配器的状态,请使用:

$ watch -n1 rfkill list all

如果开启适配器后其标识符仍然显示为 blocked,可尝试如下命令手动 unblock(其中 X 是上面输出的标识符编号):

# rfkill event unblock X

静态 IP 地址设置恢复为 DHCP

由于未解决的错误,将默认连接更改为静态 IP 地址时,nm-applet 可能无法正确存储配置更改,并将恢复为自动 DHCP。

要解决这个问题,必须在 nm-applet 中编辑默认连接(例如 "Auto eth0")、改变连接名称(例如改成 "my eth0")、取消勾选"对所有用户可用"复选框并根据需要改变静态 IP 地址设置,最后点击应用。这将保存一个具有给定名称的新连接。

接下来,要让默认连接不自动连接。要做到这一点,请以 root 身份运行 nm-connection-editor。在连接编辑器中,编辑默认连接(例如 "Auto eth0"),取消勾选"自动连接"。点击应用,然后关闭连接编辑器。

普通用户无法编辑连接

参见 #设置 PolicyKit 权限

忘记隐藏无线网络

由于隐藏网络不会显示在无线视图的选择列表中,因此无法使用 GUI 忘记(删除)它们。可以使用以下命令删除:

# rm /etc/NetworkManager/system-connections/SSID

这也适用于任何其他连接。

GNOME 中 VPN 不工作

使用 GNOME 时,在 NetworkManager 中设置 OpenConnect 或 vpnc 连接时,有时不会看到弹出对话框,并且 /var/log/errors.log 中会出现以下错误:

localhost NetworkManager[399]: <error> [1361719690.10506] [nm-vpn-connection.c:1405] get_secrets_cb(): Failed to request VPN secrets #3: (6) No agents were available for this request.

这是由于 GNOME NetworkManager Applet 期望对话框脚本位于 /usr/lib/gnome-shell,而 NetworkManager 的包将它们放入 /usr/lib/networkmanager。 作为"临时"修复(这个错误已经存在一段时间了),请创建以下符号链接:

  • 对于 OpenConnect:ln -s /usr/lib/networkmanager/nm-openconnect-auth-dialog /usr/lib/gnome-shell/
  • 对于 VPNC(即 Cisco VPN):ln -s /usr/lib/networkmanager/nm-vpnc-auth-dialog /usr/lib/gnome-shell/

对其他的 NetworkManager VPN 插件可能也需要做类似的事情,不过以上两个最常见。

无法连接到可见的欧洲无线网络

WLAN 芯片附带默认的监管区域[损坏的链接:无效的章节]。如果接入点不在这些限制范围内运行,就无法连接到网络。解决这个问题很容易:

  1. 安装 wireless-regdb
  2. 取消注释 /etc/conf.d/wireless-regdom 中正确的国家代码。
  3. 重新启动系统,因为该设置仅在启动时读取。

启动时自动连接到 VPN 不工作

当系统(即以 root 用户运行的 NetworkManager)尝试建立一个 VPN 连接时问题就会发生,因为密码存储在某一个特定用户的 GNOME Keyring 中,所以无法获取密码。

一个解决办法是用明文存储 VPN 密码,如#使用 dispatcher 在网络连接建立后连接 vpn 步骤 (2.) 中所描述。

如果使用 nm-applet GUI 中的新的"自动连接 VPN"选项,就不再需要使用步骤 (1.) 所描述的 dispatcher 自动连接。

systemd 瓶颈

随着时间的推移,日志文件(/var/log/journal)可能会变得非常庞大。使用 NetworkManager 时,这可对启动性能产生大的影响,参考:systemd (简体中文)#启动的时间太长

有规律的网络断开、延迟和丢包(WiFi)

NetworkManager 每 2 分钟扫描一次。

有些 WiFi 驱动在已连接/关联的同时扫描基站会有问题。症状包括 VPN 断开/重连和丢包,以及页面无法加载但之后刷新没有问题。

以 root 身份运行 journalctl -f 可以表明这种情况是否正在发生,类似下面的信息会在日志文件中以有规律的间隔出现:

NetworkManager[410]: <info>  (wlp3s0): roamed from BSSID 00:14:48:11:20:CF (my-wifi-name) to (none) ((none))

如果漫游不重要,可以通过在 WiFi 连接配置文件中锁定接入点的 BSSID 来禁用定期扫描行为。

Unable to turn on Wi-Fi with Lenovo laptop (IdeaPad, Legion, etc.)

There is an issue with the ideapad_laptop module on some Lenovo models due to the Wi-Fi driver incorrectly reporting a soft block. The card can still be manipulated with netctl, but managers like NetworkManager break. You can verify that this is the problem by checking the output of rfkill list after toggling your hardware switch and seeing that the soft block persists.

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: Try to use rfkill.default_state and rfkill.master_switch_mode (see kernel-parameters.html) to fix the rfkill problem. (Discuss in Talk:NetworkManager (简体中文))

Unloading the ideapad_laptop module should fix this. (warning: this may disable the laptop keyboard and touchpad also!).

不把主机名推送到DHCP服务器

NetworkManager 默认将主机名发送到 DHCP 服务器,目前界面上可以全局禁用。(Issue #584).

要针对某个连接禁用此配置,将如下内容加入配置文件:

/etc/NetworkManager/system-connections/your_connection_file
...
[ipv4]
dhcp-send-hostname=false
...
[ipv6]
dhcp-send-hostname=false
...

nm-applet disappears in i3wm

If you use the xfce4-notifyd.service for notifications you must edit the unit and add the following:

/etc/systemd/user/xfce4-notifyd.service.d/display_env.conf
[Service]
Environment="DISPLAY=:0.0"

After reloading the daemons restart xfce4-notifyd.service. Exit i3 and start it back up again and the applet should show on the tray.

Unit dbus-org.freedesktop.resolve1.service not found

If systemd-resolved.service is not started, NetworkManager will try to start it using D-Bus and fail:

dbus-daemon[991]: [system] Activating via systemd: service name='org.freedesktop.resolve1' unit='dbus-org.freedesktop.resolve1.service' requested by ':1.23' (uid=0 pid=1012 comm="/usr/bin/NetworkManager --no-daemon ")
dbus-daemon[991]: [system] Activation via systemd failed for unit 'dbus-org.freedesktop.resolve1.service': Unit dbus-org.freedesktop.resolve1.service not found.
dbus-daemon[991]: [system] Activating via systemd: service name='org.freedesktop.resolve1' unit='dbus-org.freedesktop.resolve1.service' requested by ':1.23' (uid=0 pid=1012 comm="/usr/bin/NetworkManager --no-daemon ")

This is because NetworkManager will try to send DNS information to systemd-resolved regardless of the main.dns= setting in NetworkManager.conf(5).[7]

This can be disabled with a configuration file in /etc/NetworkManager/conf.d/:

/etc/NetworkManager/conf.d/no-systemd-resolved.conf
[main]
systemd-resolved=false

See FS#62138.

Secrets were required, but not provided

If you received the following error when attempting to connect to a network:

$ nmcli device wifi connect SSID password password
Error: Connection activation failed: (7) Secrets were required, but not provided

This error can have numerous causes and you should read the journal (filter it with -u NetworkManager). For example, if NetworkManager took too long to establish connection, it will believe that the password is incorrect:

NetworkManager[1372]: <warn>  [1643991888.3808] device (wlan0): Activation: (wifi) association took too long
NetworkManager[1372]: <info>  [1643991888.3809] device (wlan0): state change: config -> need-auth (reason 'none', sys-iface-state: 'managed')
NetworkManager[1372]: <warn>  [1643991888.3838] device (wlan0): Activation: (wifi) asking for new secrets

You can try deleting the connection profile and creating a new one:

$ nmcli connection delete SSID
$ nmcli device wifi connect SSID password password

You can also try disabling MAC address randomization:

/etc/NetworkManager/conf.d/wifi_rand_mac.conf
[device]
wifi.scan-rand-mac-address=no

WPA Enterprise connection with iwd

If you try to connect to an WPA Enterprise network like 'eduroam' with NetworkManager with the iwd backend then you will get the following error from NetworkManager:

 Connection 'eduroam' is not avialable on device wlan0 because profile is not compatible with device (802.1x connections must have IWD provisioning files)

This is because NetworkManager can not configure a WPA Enterprise network. Therefore you have to configure it using an iwd configuration file /var/lib/iwd/essid.8021x like described in iwd#WPA Enterprise.

Failed to request VPN secrets

If you get this error:

Failed to request VPN secrets #1: No agents were available for this request.

It is either because the password is empty or you have to set up PolicyKit permissions.

OpenVPN connections fail with OpenSSL "ca md too weak" error

Since openssl was updated to version 3, certificates generated with legacy cryptographic algorithms are rejected by default. Attempting to use networkmanager-openvpn with such a setup can result in the following error in the logs:

nm-openvpn[14359]: OpenSSL: error:0A00018E:SSL routines::ca md too weak
nm-openvpn[14359]: Cannot load certificate file /home/archie/.local/share/networkmanagement/certificates/my_issued_cert.crt
nm-openvpn[14359]: Exiting due to fatal error

The correct approach is to have the OpenVPN server administrator generate and re-issue more secure certificates. However, as an immediate work-around, OpenVPN requires tls-cipher "DEFAULT:@SECLEVEL=0". This may not be possible through the plugin GUI, but it is possible with nmcli. Separately, you will also need to enable the legacy provider in OpenSSL.

Firstly, obtain the name of the VPN connection with the issue, from the output of the following:

$ nmcli connection show

Assuming the connection name is vpn.example.com, use nmcli like so:

$ nmcli connection modify vpn.example.com +vpn.data tls-cipher=DEFAULT:@SECLEVEL=0

The change should instantly be reflected in /etc/NetworkManager/system-connections/vpn.example.com.nmconnection.

As for OpenSSL, edit /etc/ssl/openssl.cnf as described on the OpenSSL wiki.

Specifically, at the end of the [provider_sect] section add legacy = legacy_sect. Under [default_sect] uncomment activate = 1. Lastly, add a new section [legacy_sect] that also contains the line activate = 1. Excluding most other preexisting configuration sections, the end result will look something like:

openssl_conf = openssl_init
  
[openssl_init]
providers = provider_sect
  
[provider_sect]
default = default_sect
legacy = legacy_sect
  
[default_sect]
activate = 1
  
[legacy_sect]
activate = 1

Finally, restart the NetworkManager.service to have the new OpenSSL configuration take effect.

参见