/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.
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.
3g modem not detected
See Mobile broadband modem#NetworkManager.
Appindicator
As of version 1.18.0 Appindicator support is available in the official network-manager-applet package. To use nm-applet in an Appindicator environment start the applet with the following command:
$ nm-applet --indicator
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.
Avoiding the dispatcher timeout
If the above is working, then this section is not relevant. 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.d/remain_after_exit.conf
[Service] RemainAfterExit=yes
Now start and enable the modified NetworkManager-dispatcher service.
Warning: Adding the RemainAfterExit line to it will prevent the dispatcher from closing. Unfortunately, the dispatcher has to close before it can run your scripts again. With it the dispatcher will not time out but it also will not close, which means that the scripts will only run once per boot. Therefore, do not add the line unless the timeout is definitely causing a problem.
Captive portals
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
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. The default host (configured in /usr/lib/NetworkManager/conf.d/20-connectivity.conf) is 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)
/etc/NetworkManager/conf.d/20-connectivity.conf
Configuration
NetworkManager will require some additional steps to be able run properly. Make sure you have configured /etc/hosts as described in Network configuration#Set the hostname section.
NetworkManager has a global configuration file at /etc/NetworkManager/NetworkManager.conf. Additional configuration files can be placed in /etc/NetworkManager/conf.d/. Usually no configuration needs to be done to the global defaults.
After editing a configuration file, the changes can be applied by running:
# nmcli general reload
Configuring mac address randomization
MAC randomization can be used for increased privacy by not disclosing your real MAC address to the network.
Custom dnsmasq configuration
Custom configurations can be created for dnsmasq by creating configuration files in /etc/NetworkManager/dnsmasq.d/. For example, to change the size of the DNS cache (which is stored in RAM):
/etc/NetworkManager/dnsmasq.d/cache.conf
cache-size=1000
You can check the configuration file syntax with:
dnsmasq --test --conf-file=/dev/null --conf-dir=/etc/NetworkManager/dnsmasq.d
See dnsmasq(8) for all available options.
Dhcp client
By default NetworkManager uses its internal DHCP client. The internal DHCPv4 plugin is based on the nettools’ n-dhcp4 library, while the internal DHCPv6 plugin is made from code based on systemd-networkd.
To use a different DHCP client install one of the alternatives:
To change the DHCP client backend, set the option main.dhcp=dhcp_client_name with a configuration file in /etc/NetworkManager/conf.d/. E.g.:
/etc/NetworkManager/conf.d/dhcp-client.conf
[main] dhcp=dhclient
Dhcp problems with dhclient
If you have problems with getting an IP address via DHCP, try to add the following to your /etc/dhclient.conf:
interface "eth0" { send dhcp-client-identifier 01:aa:bb:cc:dd:ee:ff; }
Where aa:bb:cc:dd:ee:ff is the MAC address of this NIC. The MAC address can be found using the ip link show interface command from the iproute2 package.
Dns caching and conditional forwarding
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.
Dns management
NetworkManager’s DNS management is described in the GNOME project’s wiki page—Projects/NetworkManager/DNS.
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.
Dnsmasq
Make sure dnsmasq has been installed. Then set main.dns=dnsmasq with a configuration file in /etc/NetworkManager/conf.d/:
/etc/NetworkManager/conf.d/dns.conf
[main] dns=dnsmasq
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
Edit a connection
For a comprehensive list of settings, see nm-settings(5).
Firstly you need to get list of connections:
$ 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 --
Here you can use the first column as connection-id used later. In this example we pick Wired connection 2 as a connection-id.
You have three methods to configure a connection Wired connection 2 after it has been created:
- nmcli interactive editor
nmcli connection edit 'Wired connection 2'
.
Usage is well documented from the editor.
- nmcli command line interface
nmcli connection modify 'Wired connection 2' setting.propertyvalue
. See nmcli(1) for usage. For example you can change its IPv4 route metric to 200 usingnmcli 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 ""
- Connection file
- In
/etc/NetworkManager/system-connections/
, modify the correspondingWired connection 2.nmconnection
file .
Do not forget to reload the configuration file withnmcli connection reload
.
Enable ipv6 privacy extensions
See IPv6#NetworkManager.
Encrypted wi-fi passwords
By default, NetworkManager stores passwords in clear text in the connection files at /etc/NetworkManager/system-connections/. To print the stored passwords, use the following command:
# grep -r '^psk=' /etc/NetworkManager/system-connections/
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.
Firewall
You can assign a firewalld zone based on your current connection. For example a restrictive firewall when at work, and a less restrictive one when at home.
This can also be done with NetworkManager dispatcher.
Forget hidden wireless network
Since hidden networks are not displayed in the selection list of the Wireless view, they cannot be forgotten (removed) with the GUI. You can delete one with the following command:
# rm /etc/NetworkManager/system-connections/SSID
This also works for any other connection.
Gnome
GNOME has a built-in tool, accessible from the Network settings.
Ignore specific devices
Sometimes it may be desired that NetworkManager ignores specific devices and does not try to configure addresses and routes for them. You can quickly and easily ignore devices by MAC or interface-name by using the following in /etc/NetworkManager/conf.d/unmanaged.conf:
[keyfile] unmanaged-devices=mac:00:22:68:1c:59:b1;mac:00:1E:65:30:D1:C4;interface-name:eth0
After editing the file, run nmcli general reload as root. Afterwards you should be able to configure interfaces without NetworkManager altering what you have set.
Installation
NetworkManager can be installed with the package networkmanager, which contains a daemon, a command line interface (nmcli) and a curses‐based interface (nmtui).
Kde plasma
Install the plasma-nm package. After that, add it to the KDE taskbar via the Panel options > Add widgets > Networks menu.
Mobile broadband support
NetworkManager uses ModemManager for mobile broadband connection support.
Installmodemmanager and usb_modeswitch. Afterwards enable and startModemManager.service.
It may be necessary to restartNetworkManager.service for it to detect ModemManager. After you restart it, re-plug the modem again and it should be recognized.
Add connections from a front-end (e.g. nm-connection-editor) and select mobile broadband as the connection type. After selecting your ISP and billing plan, APN and other settings should be filled in automatically using information from mobile-broadband-provider-info.
Modem-manager with quectel ec21
I’m running Ubuntu Core on a Raspberry Pi Compute Module 3 (and IO board), and have a Quectel EC21 LTE modem connected to it via USB. I’m struggling to get it to work.
Following the guide on the Ubuntu Core docs site, I can see the modem show up:
$ sudo modem-manager.mmcli -L
Found 1 modems: /org/freedesktop/ModemManager1/Modem/1 [Quectel] EC21
And I can see some good information about it:
$ sudo modem-manager.mmcli -m 1
/org/freedesktop/ModemManager1/Modem/1 (device id 'a7dea8991786834fd4f5937baf2bae98f64e16dd') ------------------------- Hardware | manufacturer: 'Quectel' | model: 'EC21' | revision: 'EC21AUTFAR02A03M4G' | supported: 'gsm-umts, lte' | current: 'gsm-umts, lte' | equipment id: '861108030174782' ------------------------- System | device: '/sys/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.2' | drivers: 'option1' | plugin: 'Generic' | primary port: 'ttyUSB2' | ports: 'ttyUSB0 (qcdm), ttyUSB2 (at), ttyUSB3 (at)' ------------------------- Numbers | own : 'unknown' ------------------------- Status | lock: 'none' | unlock retries: 'unknown' | state: 'connected' | power state: 'on' | access tech: 'lte' | signal quality: '80' (recent) ------------------------- Modes | supported: 'allowed: 2g, 3g, 4g; preferred: none' | current: 'allowed: 2g, 3g, 4g; preferred: none' ------------------------- Bands | supported: 'unknown' | current: 'unknown' ------------------------- IP | supported: 'ipv4, ipv6, ipv4v6' ------------------------- 3GPP | imei: '861108030174782' | enabled locks: 'none' | operator id: '50501' | operator name: 'Telstra Mobile Telstra' | subscription: 'unknown' | registration: 'home' ------------------------- SIM | path: '/org/freedesktop/ModemManager1/SIM/1' ------------------------- Bearers | paths: '/org/freedesktop/ModemManager1/Bearer/0'
If I follow the rest of the guide, i.e.:
$ sudo nmcli c add type gsm ifname ttyUSB2 con-name 4G apn telstra.internet
Connection '4G' (7640a17c-c7f4-40c7-9490-bfb0d22e28f1) successfully added.
$ sudo nmcli r wwan on
I seem to get an IP address:
$ ip addr
4: ppp0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 3 link/ppp inet 10.98.27.23/32 brd 10.98.27.23 scope global ppp0 valid_lft forever preferred_lft forever
This is the output of the logs:
$ sudo journalctl --no-pager -u snap.network-manager.networkmanager.service
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.0949] settings: Failed to add 7640a17c-c7f4-40c7-9490-bfb0d22e28f1/'4G': Plugin does not support adding connections
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.0984] keyfile: loading from file "/var/snap/network-manager/265/conf/system-connections/4G"...
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.0987] settings-connection[0x12b6590]: constructed (NMKeyfileConnection)
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1014] settings-connection[0x12b6590,7640a17c-c7f4-40c7-9490-bfb0d22e28f1]: replace settings from connection 0x754040c0 (4G)
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <info> [1523928492.1049] keyfile: add connection /var/snap/network-manager/265/conf/system-connections/4G (7640a17c-c7f4-40c7-9490-bfb0d22e28f1,"4G")
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1055] settings-connection[0x12b6590,7640a17c-c7f4-40c7-9490-bfb0d22e28f1]: failed to read connection timestamp: Key file does not have key '7640a17c-c7f4-40c7-9490-bfb0d22e28f1' in group 'timestamps'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1088] connection 'new connection' (0x12b6590/NMKeyfileConnection): [/org/freedesktop/NetworkManager/Settings/2]
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1090] connection [ 0x12fd2a8 ]
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1091] connection.id = '4G'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1092] connection.interface-name = 'ttyUSB2'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1093] connection.permissions = []
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1094] connection.secondaries = []
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1095] connection.type = 'gsm'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1096] connection.uuid = '7640a17c-c7f4-40c7-9490-bfb0d22e28f1'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1097] gsm [ 0x1332b30 ]
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1098] gsm.apn = 'telstra.internet'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1099] gsm.number = '*99#'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1100] ipv4 [ 0x1310bc8 ]
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1101] ipv4.addresses = ((GPtrArray*) 0x1303660)
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1102] ipv4.dns = []
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1103] ipv4.dns-search = []
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1104] ipv4.method = 'auto'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1105] ipv4.routes = ((GPtrArray*) 0x12f7fc8)
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1106] ipv6 [ 0x1310c90 ]
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1107] ipv6.addresses = ((GPtrArray*) 0x12f8180)
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1108] ipv6.dns = []
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1109] ipv6.dns-search = []
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1110] ipv6.method = 'auto'
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1111] ipv6.routes = ((GPtrArray*) 0x12f7478)
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1127] create NMAuditManager singleton (0x75300d50)
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <info> [1523928492.1129] audit: op="connection-add" uuid="7640a17c-c7f4-40c7-9490-bfb0d22e28f1" name="4G" pid=3186 uid=0 result="success"
Apr 17 01:28:12 localhost.localdomain NetworkManager[1489]: <debug> [1523928492.1168] Saving secrets for connection /org/freedesktop/NetworkManager/Settings/2 (4G)
Apr 17 01:28:28 localhost.localdomain NetworkManager[1489]: <debug> [1523928508.6772] manager: (WWAN): setting radio enabled by user
Apr 17 01:28:28 localhost.localdomain NetworkManager[1489]: <info> [1523928508.6842] audit: op="radio-control" arg="wwan-enabled:1" pid=3201 uid=0 result="success"
But, if I do something like ping using the ppp
interface, I get nothing:
$ sudo ping -I ppp0 8.8.8.8
What do I need to do to get the WWAN interface working?
Mount remote folder with sshfs
As the script is run in a very restrictive environment, you have to export SSH_AUTH_SOCK in order to connect to your SSH agent. There are different ways to accomplish this, see this message for more information. The example below works with GNOME Keyring, and will ask you for the password if not unlocked already.
In case NetworkManager connects automatically on login, it is likely gnome-keyring has not yet started and the export will fail (hence the sleep). The UUID to match can be found with the command nmcli connection status or nmcli connection list.
Mounting of nfs shares
See NFS#Using a NetworkManager dispatcher.
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
An alternative is to use the script as seen in NFS#Using a NetworkManager dispatcher:
/etc/NetworkManager/dispatcher.d/30-smb.sh
#!/bin/bash # 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: NetworkManager connection name, not used # Script parameter $2: dispatched event case "$2" in "up") mount -a -t cifs ;; "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
Network management disabled
When NetworkManager shuts down but the pid (state) file is not removed, you will see a Network management disabled message. If this happens, remove the file manually:
# rm /var/lib/NetworkManager/NetworkManager.state
Network services with networkmanager dispatcher
There are quite a few network services that you will not want running until NetworkManager brings up an interface. NetworkManager has the ability to start services when you connect to a network and stop them when you disconnect (e.g. when using NFS, SMB and NTPd).
To activate the feature you need to enable and start the NetworkManager-dispatcher.service.
Once the service is active, scripts can be added to the /etc/NetworkManager/dispatcher.d directory.
Scripts must be owned by root, otherwise the dispatcher will not execute them. For added security, set group ownership to root as well:
# chown root:root /etc/NetworkManager/dispatcher.d/10-script.sh
Make sure the file has correct permissions:
# chmod 755 /etc/NetworkManager/dispatcher.d/10-script.sh
The scripts will be run in alphabetical order at connection time, and in reverse alphabetical order at disconnect time. To ensure what order they come up in, it is common to use numerical characters prior to the name of the script (e.g. 10-portmap or 30-netfs (which ensures that the portmapper is up before NFS mounts are attempted).
Scripts will receive the following arguments:
Warning: If you connect to foreign or public networks, be aware of what services you are starting and what servers you expect to be available for them to connect to. You could make a security hole by starting the wrong services while connected to a public network.
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)).
[Service] ExecStart= ExecStart=/usr/bin/nm-online -q
Be aware that this can cause other issues.
In some cases, the service will still fail to start successfully on boot due to the timeout setting being too short. Edit the service to change NM_ONLINE_TIMEOUT from 60 to a higher value.
Nm-applet
network-manager-applet is a GTK 3 front-end which works under Xorg environments with a systray.
To store connection secrets install and configure GNOME/Keyring.
Nm-applet disappears in i3wm
If you use the xfce4-notifyd.service for notifications you must edit the unit and add the following:
Nmcli examples
List nearby Wi-Fi networks:
$ nmcli device wifi list
Connect to a Wi-Fi network:
$ nmcli device wifi connect SSID_or_BSSID password password
Connect to a hidden Wi-Fi network:
$ nmcli device wifi connect SSID_or_BSSID password password hidden yes
Connect to a Wi-Fi on the wlan1 interface:
$ nmcli device wifi connect SSID_or_BSSID password password ifname wlan1 profile_name
Disconnect an interface:
$ nmcli device disconnect ifname eth0
Get a list of connections with their names, UUIDs, types and backing devices:
$ nmcli connection show
Activate a connection (i.e. connect to a network with an existing profile):
$ nmcli connection up name_or_uuid
Delete a connection:
$ nmcli connection delete name_or_uuid
See a list of network devices and their state:
$ nmcli device
Turn off Wi-Fi:
$ nmcli radio wifi off
No prompt for password of secured wi-fi networks
When trying to connect to a secured Wi-Fi network, no prompt for a password is shown and no connection is established. This happens when no keyring package is installed. An easy solution is to install gnome-keyring.
Openntpd
See OpenNTPD#Using NetworkManager dispatcher.
Pppoe / dsl support
Installrp-pppoe package for PPPoE / DSL connection support. To actually add PPPoE connection, use nm-connection-editor and add new DSL/PPPoE connection.
Problems with internal dhcp client
If you have problems with getting an IP address using the internal DHCP client, consider using another DHCP client, see #DHCP client for instructions. This workaround might solve problems in big wireless networks like eduroam.
Proxy settings
NetworkManager does not directly handle proxy settings, but if you are using GNOME or KDE, you could use proxydriver which handles proxy settings using NetworkManager’s information. proxydriver is found in the package proxydriverAUR.
In order for proxydriver to be able to change the proxy settings, you would need to execute this command, as part of the GNOME startup process (see GNOME#Autostart).
Regular network disconnects, latency and lost packets (wifi)
NetworkManager does a scan every 2 minutes.
Some WiFi drivers have issues when scanning for base stations whilst connected/associated. Symptoms include VPN disconnects/reconnects and lost packets, web pages failing to load and then refresh fine.
Running journalctl -f as root will indicate that this is taking place, messages like the following will be contained in the logs at regular intervals.
NetworkManager[410]: <info> (wlp3s0): roamed from BSSID 00:14:48:11:20:CF (my-wifi-name) to (none) ((none))
There is a patched version of NetworkManager which should prevent this type of scanning: networkmanager-noscanAUR.
Alternatively, if roaming is not important, the periodic scanning behavior can be disabled by locking the BSSID of the access point in the WiFi connection profile.
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.
Secrets were required, but not provided
If you attempt to connect to a network using nmcli device wifi connect SSID password password and received the following error:
Error: Connection activation failed: (7) Secrets were required, but not provided
The error can be resolved by 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
Set up policykit permissions
See General troubleshooting#Session permissions for setting up a working session.
With a working session, you have several options for granting the necessary privileges to NetworkManager:
Setting custom dns servers in a connection (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, ….
Setting custom dns servers in a connection (nmcli / connection file)
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.
Setting custom global dns servers
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
Sharing internet connection over ethernet
Scenario: your device has internet connection over wi-fi and you want to share the internet connection to other devices over ethernet.
Requirements:
Steps:
- Run
nm-connection-editor
from terminal. - Add a new ethernet connection.
- Give it some sensible name. For example “Shared Internet”
- Go to “IPv4 Settings”.
- For “Method:” select “Shared to other computers”.
- Save
Now you should have a new option “Shared Internet” under the Wired connections in NetworkManager.
Sharing internet connection over wi-fi
You can share your internet connection (e.g. 3G or wired) with a few clicks. Please note that a firewall may interfere with internet sharing.
You will need a Wi-Fi card which supports AP mode, see Software access point#Wi-Fi device must support AP mode for details.
Install the dnsmasq package to be able to actually share the connection. Note that NetworkManager starts its own instance of dnsmasq, independent of dnsmasq.service, as a DHCP server. See #dnsmasq for the caveats.
Create the shared connection:
The connection will be saved and remain stored for the next time you need it.
Note: Android does not support connecting to Ad-hoc networks. To share a connection with Android use infrastructure mode (i.e. set Wi-Fi mode to “Hotspot”).
Static ip address settings revert to dhcp
Due to an unresolved bug, when changing default connections to a static IP address, nm-applet may not properly store the configuration change, and will revert to automatic DHCP.
Switching off wlan on laptops
Sometimes NetworkManager will not work when you disable your Wi-Fi adapter with a switch on your laptop and try to enable it again afterwards. This is often a problem with rfkill. To check if the driver notifies rfkill about the wireless adapter’s status, use:
$ watch -n1 rfkill list all
Systemd-resolved
NetworkManager can use systemd-resolved as a DNS resolver and cache. Make sure that systemd-resolved is properly configured and that systemd-resolved.service is started before using it.
You can enable it explicitly by setting main.dns=systemd-resolved with a configuration file in /etc/NetworkManager/conf.d/:
/etc/NetworkManager/conf.d/dns.conf
[main] dns=systemd-resolved
Unable to connect to visible european wireless networks
WLAN chips are shipped with a default regulatory domain. If your access point does not operate within these limitations, you will not be able to connect to the network. Fixing this is easy:
- Installcrda
- Uncomment the correct Country Code in
/etc/conf.d/wireless-regdom
- Reboot the system, because the setting is only read on boot
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).[8]
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.
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
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.
Usage
NetworkManager comes with nmcli(1) and nmtui(1).
Use dispatcher to connect to a vpn after a network connection is established
/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
If you would like to attempt to automatically connect to VPN for all Wi-Fi networks, you can use the following definition of the ESSID: ESSID=$(iwgetid -r). Remember to set the script’s permissions accordingly.
Trying to connect with the above script may still fail with NetworkManager-dispatcher.service complaining about ‘no valid VPN secrets’, because of the way VPN secrets are stored. Fortunately, there are different options to give the above script access to your VPN password.
1: One of them requires editing the VPN connection configuration file to make NetworkManager store the secrets by itself rather than inside a keyring that will be inaccessible for root: open up /etc/NetworkManager/system-connections/name of your VPN connection and change the password-flags and secret-flags from 1 to 0.
If that alone does not work, you may have to create a passwd-file in a safe location with the same permissions and ownership as the dispatcher script, containing the following:
/path/to/passwd-file
vpn.secrets.password:YOUR_PASSWORD
The script must be changed accordingly, so that it gets the password from the file:
/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: Alternatively, change the password-flags and put the password directly in the configuration file adding the section vpn-secrets:
[vpn] .... password-flags=0 [vpn-secrets] password=your_password
Note: It may now be necessary to re-open the NetworkManager connection editor and save the VPN passwords/secrets again.
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
Use openresolv
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
Using gnome keyring
The keyring daemon has to be started and the keyring needs to be unlocked for the following to work.
Vpn not working in gnome
When setting up OpenConnect or vpnc connections in NetworkManager while using GNOME, you will sometimes never see the dialog box pop up and the following error appears in /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.
This is caused by the GNOME NM Applet expecting dialog scripts to be at /usr/lib/gnome-shell, when NetworkManager’s packages put them in /usr/lib/networkmanager.
As a “temporary” fix (this bug has been around for a while now), make the following symlink(s):
- For OpenConnect:
ln -s /usr/lib/networkmanager/nm-openconnect-auth-dialog /usr/lib/gnome-shell/
- For VPNC (i.e. Cisco VPN):
ln -s /usr/lib/networkmanager/nm-vpnc-auth-dialog /usr/lib/gnome-shell/
This may need to be done for any other NM VPN plugins as well, but these are the two most common.
Vpn support
NetworkManager since version 1.16 has native support for WireGuard, all it needs is the wireguard kernel module. Read the WireGuard in NetworkManager blog post for details.
Support for other VPN types is based on a plug-in system. They are provided in the following packages:
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.
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 config file /var/lib/iwd/essid.8021x like described in iwd#WPA Enterprise.
Как подключить 3g usb модем (мегафон, мтс, билайн) в ubuntu linux 12.04
В этой статье будет рассмотрена настройка и подключение 3G USB модема
(МТС, Мегафон) в Ubuntu 12.04. Это предельно
простая инструкция как подключить сотовый 3G модем в графической среде
Unity, с использованием интерфейса
Network Manager. Инструкция применима не только к
Ubuntu установленной на жесткий диск, но и к
Live варианту запускаемому с
USB флешки или с лазерного диска.
В Linux, в графических оболочках
Gnome, KDE, XFCE, Unity в качестве графического
интерфейса для настройки сетевых подключений используется программа Network Manager. Точнее Network
Manager обеспечивает plug and play работу с
физическими сетевыми устройствами, а графический интерфейс этой программы
называется Network Manager
Applet (nm-applet). Network Manager
Applet отображается в виде значка в системном трее
и если на этом значке кликнуть мышью откроется меню с функциями программы:
Для подключения 3G USB модема нужно воткнуть модем в USB разъем
компьютера и через 1-2 минуты (необходимо некоторое время на то, чтобы модем
был опознан системой и подключен) кликнуть на значке “Сеть” в трее и выбрать
пункт меню “Edit connections” (иллюстрация
выше). В результате откроется окно, в котором
нужно выбрать вкладку “Mobile broadband”
и там нажать кнопку “Add”:
Запустится мастер настройки соединения, в первом окне нажать кнопку
“Continue”:
Примечание.
Если вкладка “Широкополосный доступ (Mobile
broadband)” недоступна или в первом окне
настройки не определена модель модема, тогда:
нужно добавить новую строку в файле /lib/udev/rules.d/40-usb_modeswitch.rules
в которой прописать vid и pid вашего модема. Эти данные вы можете
узнать через консоль командой lsusb.
Во втором окне выбрать страну и нажать кнопку
“Continue”:
В следующем окне выбрать оператора и нажать кнопку
“Continue”:
В следующем окне нажать кнопку “Continue”:
В следующем окне нажать кнопку “Apply”:
В следующем окне нажать кнопку “Save”:
В этом окне можно отключить опцию “Allow roaming …”
(роуминг) и включить опцию “Connect automatically”.
Готово. Теперь, для того чтобы подключиться к Интернет достаточно
кликнуть на значке “Сеть” и в меню выбрать название созданного соединения:
И через несколько секунд соединение будет установлено:
Можно сделать так, чтобы соединение устанавливалось автоматически, как
только модем будет воткнут в USB разъем. Для этого
необходимо открыть окно соединений, выбрать вкладку “Mobile
broadband” и там нажать кнопку “Edit”
затем отметить опцию “Connect automatically”
и нажать кнопку “Save”:
P.S.
По моим длительным наблюдениям в Ubuntu
“сотовый” Интернет работает немного быстрее чем в Windows.
Бывает даже и такое, что в Windows соединения
вообще нет (оно устанавливается но не работает), а в
Ubuntu все нормально.
Если у вас возникли проблемы с подключением читайте другую статью –
установка и настройка 3G USB модема на Ubuntu
Linux, в ней более подробно описан процесс установки и настройки.
Иван Сухов, 2021 г.
Часть вторая — подключаемся
Собственно, программ, которые позволяют заставить модем набрать номер и подключиться к провайдеру — предостаточно. Тот же Network Manager, например. Кстати, те, у кого до этого в Network Managere-е модем не находился, уже могут попробовать поискать его снова 😉 . Ну а мы, в данном случае, решили воевать в консоли. Потому, в консоли и продолжим…
Программу я для этого решил использовать следующую — wvdial. По умолчанию она не установлена, поэтому, устанавливаем:
Часть первая — ищем сам модем!
Много современных USB-модемов для 3G сетей являются «составным USB-устройством». То есть, в таком многофункциональном «USB-свистке» присутствует как сам модем, так и виртуальный компакт-диск с драйверами и ПО, плюс, у ряда моделей — картридер, а также служебный интерфейс, который нас в данном случае не интересует вовсе.
dmitry@hotspot-server:~$ lsusbBus 001 Device 002: ID 19d2:2000Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Как показано выше, в ответ на наш запрос система выдала список обнаруженных ей USB устройств с их идентификаторами. В ответе я выделил идентификатор только что подключенного мной модема. Красным он выделен потому, что это идентификатор не модемной части, а виртуального CDROM-а. То есть, нам нужно что-то сделать с этим устройством, чтобы оно переключилось из CDROM-а в модем.
Програмное решение для этой цели уже давно существует. Оно называется usb-modeswitch, и на сегодняшний день включено в большинство современных дистрибутивов Linux. И вот теперь, я вернусь к тому, почему был выбран такой старый дистрибутив — в дистрибутиве Ubuntu 9.
dmitry@hotspot-server:/usr/src/usb$ sudo apt-get install usb-modeswitchЧтение списков пакетов... Готово Построение дерева зависимостей Чтение информации о состоянии... Готово E: Не удалось найти пакет usb-modeswitch
Очень жаль, ибо без него нам никак!
ВНИМАНИЕ: Еще раз повторюсь — речь идет именно про дистрибутив Ubuntu 9.04 (и возможно, более старые версии, но я не проверял)! Если же у вас дистрибутив Ubuntu 9.10 и новее, то описанные ниже действия по ручному скачиванию пакетов и ручной же их установке вам не нужны.
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
Turn off hostname sending
NetworkManager by default sends the hostname to the DHCP server. Hostname sending can only be disabled per connection not globally (Issue #584).
To disable sending your hostname to the DHCP server for a specific connection, add the following to your network connection file:
/etc/NetworkManager/system-connections/your_connection_file
... [ipv4] dhcp-send-hostname=false ... [ipv6] dhcp-send-hostname=false ...
Using iwd as the wi-fi backend
Enable the experimentaliwd backend creating 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.