NetworkManager (简体中文)

From ArchWiki
Revision as of 04:05, 14 November 2012 by Fengchao (Talk | contribs) (设置 PolicyKit 权限: Update for systemd.)

Jump to: navigation, search

Template:Article summary start Template:Article summary text Template:Article summary heading Template:Article summary text Template:Article summary end

Tango-preferences-desktop-locale.png本页面需要更新翻译,内容可能已经与英文脱节。要贡献翻译,请访问简体中文翻译组Tango-preferences-desktop-locale.png

附注: please use the first argument of the template to provide more detailed indications.

网络管理器(NetworManager)是检测网络、自动连接网络的程序。无论是无线还是有线连接,它都可以令您轻松管理。对于无线网络,网络管理器可以自动切换到最可靠的无线网络。利用网络管理器的程序可以自由切换在线和离线模式。网络管理器可以优先选择有线网络,支持 VPN。网络管理器最初由 Redhat 公司开发,现在由 GNOME 管理。

安装

NetworkManager 可以在接在 [extra] 源中进行安装

# pacman -S networkmanager

图形前端

为了方便使用网络管理器进行管理和配置,通常需要安装托盘组件。 图形前端往往显示在系统托盘(或通知区域),从而允许用户选择网络或者配置 NetworkManager。 各种桌面环境的安装方法如下:

Gnome环境

Gnome’s applet (原gnome-network-manager)是一个轻量级的全能组件,几乎可以运行在所有的桌面环境下。

# pacman -S network-manager-applet

如果你想储存验证信息(Wireless/DSL),并提供给所有用户使用,那么您还需要安装:

# pacman -S gnome-keyring

KDE4

目前已经提供对KDE4的支持

# pacman -S kdeplasma-applets-networkmanagement

这个 KDE 组件功能和 GNOME 中的一样可以工作,甚至表现的更好(比如提供更多的功能,更多的硬件支持)。

注意: 如果您是从另一个网络管理器改变过来的,比如WICD,请不要忘记在 System Settings -> Hardware -> Information Sources中将NetworkManager设置为默认的网络管理器。

如果同时安装了 KNetworkManager 和 nm-applet,在使用 KDE 时不想使用 nm-applet,将下行加入 /etc/xdg/autostart/nm-applet.desktop

NotShowIn=KDE

KDE3

虽然不再支持,但仍旧可以在可以在AUR软件仓中找到,包名称为 knetworkmanagerAUR

XFCE

nm-applet 可以在 XFCE 下正常工作,但是为了可以显示通知信息,包括错误信息, nm-applet 需要一个 Freedesktop 桌面通知扩展(查阅 [1])。xfce4-notifyd 就是这么一个扩展。

# pacman -S network-manager-applet xfce4-notifyd

如果这个扩展没有运行守护进程,nm-applet 就会输出下面的错误到 stdout/stderr:

(nm-applet:24209): libnotify-WARNING **: Failed to connect to proxy
** (nm-applet:24209): WARNING **: get_all_cb: couldn't retrieve
system settings properties: (25) Launch helper exited with unknown
return code 1.
** (nm-applet:24209): WARNING **: fetch_connections_done: error
fetching connections: (25) Launch helper exited with unknown return
code 1.
** (nm-applet:24209): WARNING **: Failed to register as an agent:
(25) Launch helper exited with unknown return code 1

尽管没有通知系统,nm-applet 仍然会正常工作。

Openbox

GNOME applet 和 xfce4-notifyd 结合可以很好的工作:

# pacman -S network-manager-applet xfce4-notifyd hicolor-icon-theme gnome-icon-theme

如果你想储存验证信息(Wireless/DSL),请安装:

# pacman -S gnome-keyring

要让 Openbox autostart 启动 nm-applet,需要删除文件/etc/xdg/autostart/nm-applet.desktop。每次更新 network-manager-applet 都需要删除这个文件。 在 autostart 中加入:

# (sleep 3 && /usr/bin/nm-applet --sm-disable) &

其它桌面和窗口管理器

推荐使用 GNOME 组件,需要安装 GNOME hicolor 主题:

# pacman -S hicolor-icon-theme gnome-icon-theme

不使用系统托盘,可以使用 trayer 或 stalonetray。例如,在路径中加入 "nmgui" 脚本:

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

关闭 stalonetray 窗口时,将会同时关闭 nm-applet,所以完成网络设置后不会使用额外的内存。

命令行

网络管理器 0.8.1 版之后包含 nmcli

配置

NetworkManager 需要做这么几步保证正常运行。

先验证 /etc/hosts 配置正确,如果配置不正确,网络管理器可能修改它。示例:

#<ip-address> <hostname.domain.org>           <hostname>                        
127.0.0.1     localhost.localdomain localhost dell-latitude

禁用当前网络设置

要测试网络管理器,先停止当前网络:

# /etc/rc.d/network stop

停止网卡(使用 iproute2 软件包):

ip link set down eth0
ip link set down wlan0

编辑 /etc/rc.conf 将配置 DHCP 或静态 IP 的地方注释掉:

Note: Following settings are obsolete in the most recent rc.conf.
#eth0="dhcp"                                                                    
#wlan0="dhcp"                                                                   
INTERFACES=(!eth0 !wlan0)

编辑守护进程

删除 默认的 network 并添加 networkmanager 到 dbus 之后:

DAEMONS=( ...dbus networkmanager... )

请确保 dbus 已经安装,网络管理器需要它。尽管这里启动了网络管理器,但是如果没有应用组件启用网络,默认并不会连接网络。

设置 PolicyKit 权限

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:

Option 1. Run a PolicyKit authentication agent when you log in, such as /usr/lib/polkit-gnome/polkit-gnome-authentication-agent-1 (part of polkit-gnome). You will be prompted for your password whenever you add or remove a network connection.

Option 2. Add yourself to the wheel group. You will not have to enter your password, but your user account may be granted other permissions as well, such as the ability to use sudo without entering the root password.

Option 3. Add yourself to the network group and create the following file:

/etc/polkit-1/localauthority/50-local.d/org.freedesktop.NetworkManager.pkla
[nm-applet]
Identity=unix-group:network
Action=org.freedesktop.NetworkManager.*
ResultAny=yes
ResultInactive=no
ResultActive=yes

All users in the network group will be able to add and remove networks without a password. This will not work under systemd if you do not have an active session with systemd-logind.

网络分配器

有些服务只有联网时才有意义,例如 openntpd 网络文件系统挂载(netfs)。网络管理器可以在连接网络后启动这些服务,并在网络关闭时停止它们。

要使用这个功能,可以将脚本加到 /etc/NetworkManager/dispatcher.d 目录。这些脚本需要有可执行和用户权限。为了安全,可以设置为属于 root:root 并且只有用户可写。禁用组和其它的写权限,使用 755 mask。否则可能无法执行脚本,在 /var/log/messages.log

nm-dispatcher.action: Script could not be executed: writable by group or other, or set-UID

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

下面脚本启动 openntpd,保存为文件 /etc/NetworkManager/dispatcher.d/20_openntpd 并加上执行权限。

#!/bin/sh

INTERFACE=$1 # The interface which is brought up or down
STATUS=$2 # The new state of the interface

case "$STATUS" in
    'up') # $INTERFACE is up
	exec /etc/rc.d/openntpd start
	;;
    'down') # $INTERFACE is down
	# Check for active interface and down if no one active
	if [ ! `nm-tool|grep State|cut -f2 -d' '` = "connected" ]; then
		exec /etc/rc.d/openntpd stop
	fi
	;;
esac
警告: 如果没有连接到外部网络,请注意启动的服务和需要它们的程序。如果连接公共网络时启动了错误的服务,可能导致安全问题。

Start openntpd

The following example starts openntpd when an interface is brought up. Save the file as /etc/NetworkManager/dispatcher.d/20_openntpd and make it executable.

#!/bin/sh

INTERFACE=$1 # The interface which is brought up or down
STATUS=$2 # The new state of the interface

case "$STATUS" in
    'up') # $INTERFACE is up
	exec /etc/rc.d/openntpd start
	;;
    'down') # $INTERFACE is down
	# Check for active interface and down if no one active
	if [ ! `nm-tool|grep State|cut -f2 -d' '` = "connected" ]; then
		exec /etc/rc.d/openntpd stop
	fi
	;;
esac

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 here 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 automaticaly 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 in /etc/NetworkManager/system-connections/).

#!/bin/bash
USER=<your sshfs user>
if [ $CONNECTION_UUID == <connection UUID> ]; then
        case "$2" in

                up)
                   #sleep 10
                   export SSH_AUTH_SOCK=$(find /tmp/keyring-*/ -type s -user $USER -group users -name ssh)
                   su $USER -c "/usr/bin/sshfs user@host:/remote/folder /local/folder/"
                 ;;

                down)
                   fusermount -u /local/folder
                 ;;
        esac
 fi

使用分配器在网络连接建立后连接 vpn

In this example we want to connect automatically to a vpn-connection we defined previously with NetworkManager. First thing to to is to create the dispatcher-script that defines what to do after we connected to the network.

1. Create the dispatcher script in /etc/NetworkManager/dispatcher.d/vpn-up

case "$2" in
       up)
               sudo -u username DISPLAY=:0 /usr/bin/python /etc/NetworkManager/vpn-up.py
               ;;
esac

Remember to make it executable with chmod +x and change username to the right one.

2. Create the /etc/NetworkManager/vpn-up.py and change network-ESSID to the desired one.

Now NetworkManager should try to connect to your vpn which you had defined in your profile.

More recent versions of NetworkManager have seen a change in the python interface used in the above script, so it may no longer function. An alternative solution, however, can be found in clever use of nmcli.

#! /bin/bash

REQUIRED_CONNECTION_NAME=""
VPN_CONNECTION_NAME=""


activ_con=$(nmcli con status | grep "${REQUIRED_CONNECTION_NAME}")
activ_vpn=$(nmcli con status | grep "${VPN_CONNECTION_NAME}")
if [ "${activ_con}" -a ! "${activ_vpn}" ];
then
    nmcli con up id "${VPN_CONNECTION_NAME}"
fi

代理设置

Network Manager does not directly handle proxy settings, but if you are using GNOME, you could use proxydriver wich handles proxy settings using Network Manager's informations. Package proxydriverAUR is in the AUR.

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 ( System->Preferences->Startup Applications):

xhost +si:localuser:your_username

See: Proxy settings

测试

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

/etc/rc.d/networkmanager start

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


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

nm-applet --sm-disable &

For static IPs you will have to configure NetworkManager to understand them. The process usually involves right-clicking the applet and selecting something like 'Edit Connections'.

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

Troubleshooting

Some fixes to common problems.

No traffic via PPTP tunnel

PPTP connection logins successfully, you see ppp0 interface with correct VPN IP, but you can't even ping remote IP. It's due to lack of MPPE (Microsoft Point-to-Point Encryption) support in stock Arch pppd.

Just install ppp-mppeAUR packet from the AUR.

Network Management Disabled

Sometimes when NM shuts down the pid (state) file does not get removed and you will get a 'Network management disabled' message. If this happens, you'l have to remove it manually:

rm /var/lib/NetworkManager/NetworkManager.state

If this happens upon reboot, you can add an action to your etc/rc.local to have it removed upon bootup:

nmpid=/var/lib/NetworkManager/NetworkManager.state
[ -f $nmpid ] && rm $nmpid

NetworkManager prevents DHCPCD from using resolv.conf.head and resolv.conf.tail

Sometimes it's problematic to add static items to resolv.conf when it's constantly rewritten by nm and dhcpcd. You can use networkmanager-dhclient package from AUR but a better solution is to use this simple script:

#!/bin/bash
# 
# /etc/NetworkManager/dispatcher.d/99-resolv.conf-head_and_tail
# Include /etc/resolv.conf.head and /etc/resolv.conf.tail to /etc/resolv.conf
#
# scripts in the /etc/NetworkManager/dispatcher.d/ directory
# are called alphabetically and are passed two parameters:
# $1 is the interface name, and $2 is ¿?up¿? or ¿?down¿? as the
# case may be.

resolvconf='/etc/resolv.conf';
cat "$resolvconf"{.head,,.tail} 2>/dev/null > "$resolvconf".tmp
mv -f "$resolvconf".tmp "$resolvconf"

Preserving changes to resolv.conf

NetworkManager will attempt to write DNS information from DHCP into /etc/resolv.conf, overwriting the existing contents. To prevent this, you can set the immutable bit on the file (as root):

# chattr +i /etc/resolv.conf

To modify the file in the future, first remove the immutable bit:

# chattr -i /etc/resolv.conf

DHCP problems

If you have problems with getting an IP 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-adress of this NIC.

For some (incompliant?) routers, you will not be able to connect properly unless you comment the line

require dhcp_server_identifier

in /etc/dhcpcd.conf (note that this file is distinct from dhcpd.conf). This shouldn't cause issues unless you have multiple DHCP servers on your network (not typical); see this page for more information.

Missing default route

On at least one KDE4 system, no default route was created when establishing wireless connections with NetworkManager. Changing the route settings of the wireless connection to remove the default selection "Use only for resources on this connection" solved the issue.

3G modem not detected

If NetworkManager (from v0.7.999) does not detect your 3G modem, but you still can connect using wvdial, try installing modemmanager package using pacman -S modemmanager and restart NetworkManager daemon with /etc/rc.d/networkmanager restart. Replug your modem or restart. This utility provides support for hardware not in networkmanager's default database.

VPN problems in Networkmanager 0.7.999

If you get the error message "invalid secrets" when trying to connect to your VPN provider using the PPTP protocol, try installing the git versions instead: networkmanager, nm-applet and the pptp plugin.

Switching off WLAN on laptops

Sometimes networkmanager won't work when you disable your Wifi-adapter with a switch on your laptop and try to enable it again afterwards. This is often a problem with rfkill. Install rfkill from the repo:

# pacman -S rfkill

and use

$ watch -n1 rfkill list all

to check if the driver notifies rfkill about the wireless adapter's status. If one identifier stays blocked after you switch on the adapter you could try to manually unblock it with (where X is the number of the identifier provided by the above output):

# rfkill event unblock X

Static IP Settings Revert To DHCP

Due to an unresolved bug, when changing default connections to static IP, nm-applet may not properly store the configuration change, and will revert to automatic DHCP. A workaround for this issue follows.

Edit the default connection (eg "Auto eth0") in nm-applet. Change the connection name (eg "my eth0"), uncheck the "Available to all users" checkbox, change your static IP settings as desired, and click Apply. This will save a new connection with the given name.

Next, you will want to make the default connection not connect automatically. To do so, run

$ sudo nm-connection-editor  # you must use sudo, not su

In the connection editor, edit the default connection (eg "Auto eth0") and uncheck "Connect automatically". Click Apply and close the connection editor.

Can't edit connections as normal user

Sometimes you can connect to a new network, but after you can't edit this same connection, unless you enter the root password

Add your user in the network group. And then write a new polkit rule containing the following:

[nm-applet]
Identity=unix-group:network
Action=org.freedesktop.NetworkManager.*
ResultAny=yes
ResultInactive=no
ResultActive=yes

in the /etc/polkit-1/localauthority/50-local.d/org.freedesktop.NetworkManager.pkla file.

Tips and tricks

Checking if networking is up inside a cron job or script

Some cron jobs require networking to be up to succeed. You may wish to avoid running these jobs when the network is down. To accomplish this, add an if test for networking that queries NetworkManager's nm-tool and checks the state of networking. The test shown here succeeds if any interface is up, and fails if they are all down. This is convenient for laptops that might be hardwired, might be on wireless, or might be off the network.

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

This useful for a cron.hourly script that runs fpupdate for the F-Prot virus scanner signature update, as an example. Another way it might be useful, with a little modification, is to differentiate between networks using various parts of the output from nm-tool; for example, since the active wireless network is denoted with an asterisk, you could grep for the network name and then grep for a literal asterisk.

Automatically unlock keyring after login

Gnome

  1. Right click on the NM icon in your panel and select Edit Connections and open the Wireless tab
  2. Select the connection you want to work with and click the Edit button
  3. Check the boxes ¿?Connect Automatically¿? and ¿?Available to all users¿?

Log out and log back in to complete.

Note: The following method is dated and known not to work on at least one machine!

*In /etc/pam.d/gdm (or your corresponding daemon in /etc/pam.d), add these lines at the end of the "auth" and "session" blocks if they do not exist already:

 auth            optional        pam_gnome_keyring.so
 session         optional        pam_gnome_keyring.so  auto_start
  • In /etc/pam.d/passwd, use this line for the 'password' block:
 password    optional    pam_gnome_keyring.so
Next time you log in, you should be asked if you want the password to be unlocked automatically on login.

KDE

Note: See http://live.gnome.org/GnomeKeyring/Pam for reference, and if you are using kde / kdm, you can use pam-keyring-tool from the AUR.
  • Put a script like the following in ~/.kde4/Autostart:
 $!/bin/sh
 echo PASSWORD | /usr/bin/pam-keyring-tool --unlock --keyring=default -s
Similar should work with openbox, lxde, etc.

SLiM login manager

  • In /etc/pam.d/slim, add these lines at the end of the "auth" and "session" blocks if they do not exist already:
 auth            optional        pam_gnome_keyring.so
 session         optional        pam_gnome_keyring.so  auto_start
  • In /etc/pam.d/passwd, use this line for the 'password' block:
 password    optional    pam_gnome_keyring.so
  • In ~/.xinitrc, add this at the very top, before launching your window manager and other applications:
 ## test for an existing bus daemon, just to be safe
 if test -z "$DBUS_SESSION_BUS_ADDRESS" ; then
    ## if not found, launch a new one
    eval `dbus-launch --sh-syntax --exit-with-session`
    echo "D-Bus per-session daemon address is: $DBUS_SESSION_BUS_ADDRESS"
 fi
Next time you log in, you should be asked if you want the password to be unlocked automatically on login.

Ignore specific devices

Sometimes it may be desired that NetworkManager ignores specific devices and doesn't try to configure addresses and routes for them.

You can quickly and easily ignore devices by MAC by using the following in /etc/NetworkManager/NetworkManager.conf :

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

After you've put this in, restart NetworkManager, and you should be able to configure interfaces without NetworkManager altering what you've set.

If that isn't appropriate, you could ignore by HAL.

  • First you have to find out the Hal UDI (e.g. with lshal):
 ...
 info.product = 'Networking Interface'  (string)
 info.subsystem = 'net'  (string)
 info.udi = '/org/freedesktop/Hal/devices/net_00_1f_11_01_06_55'  (string)
 linux.hotplug_type = 2  (0x2)  (int)
 linux.subsystem = 'net'  (string)
 ...
  • Add the udi to /etc/NetworkManager/nm-system-settings.conf:
 [keyfile]
   unmanaged-devices=/org/freedesktop/Hal/devices/net_00_1f_11_01_06_55
Multiple devices can be specified, delimited by semicolons:
 [keyfile]
   unmanaged-devices=/org/freedesktop/Hal/devices/net_00_1f_11_01_06_55;/org/freedesktop/Hal/devices/net_00_2c_6d_e2_08_af

You do not need to restart NetworkManager for the changes to take effect.

  • Ignoring a type of device at boot time.

this script was used to ignore all ethernet devices at boot time of a archiso build, it can be changed to ignore wifi devices etc. /!\being used on a non-persistant filesystem, the nm-system-settings.conf is default at run time

  #!/bin/sh
  # author: tim noise <darknoise@drkns.net>
  COUNT=0
  TARGET_FILE="/etc/NetworkManager/nm-system-settings.conf"
  for i in `lshal | grep -A6 'Networking Interface' | awk -F "'" '/info.udi = / {print $2}'`; do
      if [ $COUNT = 0 ]; then
          COUNT=$COUNT+1;
          echo "unmanaged-devices=$i" >> $TARGET_FILE
      else
          echo -n ";$i" >> $TARGET_FILE
      fi
  done
  printf "\n" >> $TARGET_FILE

Connect faster

Disabling IPv6

Slow connection or reconnection to the network may be due to superfluous IPv6 queries in NetworkManager. If there is no IPv6 support on the local network, connecting to a network may take longer than normal while Network Manager tries to establish an IPv6 connection that eventually times out. The solution is to disable IPv6 within NetworkManager which will make network connection faster. This has to be done once for every network you connect to.

  • Right-click on the network status icon.
  • Click on "Edit Connections".
  • Go to the "Wired" or "Wireless" tab, as appropriate.
  • Select the name of the network.
  • Click on "Edit".
  • Go to the "IPv6 Settings" tab.
  • In the "Method" dropdown, choose "Ignore".
  • Click on "Save".

Speed up DHCP by disabling ARP probing in dhcpcd

dhcpcd contains an implementation of a recommendation of the DHCP standard (RFC2131 section 2.2) to check via ARP if the assigned IP address is really not taken. This seems mostly useless in home networks, so you can save about 5 seconds on every connect by adding the following line to /etc/dhcpcd.conf:

noarp

This is equivalent to passing --noarp to dhcpcd, and disables the described ARP probing, speeding up connections to networks with DHCP.

Use OpenDNS Servers

Create /etc/resolv.conf.opendns with the nameservers:

nameserver 208.67.222.222
nameserver 208.67.220.220

And have the dispatcher replace the discovered DHCP servers with the OpenDNS ones:

/etc/NetworkManager/dispatcher.d/dns-servers-opendns
#!/bin/bash
# Use OpenDNS servers over DHCP discovered servers

cp -f /etc/resolv.conf.opendns /etc/resolv.conf

Make the script executable:

# chmod +x /etc/NetworkManager/dispatcher.d/dns-servers-opendns

其它资源