NetworkManager (Русский)
Contents |
Введение
Network Manager - набор инструментов, которые облегчают настройку сети как проводной, так и беспроводной.
Network Manager 0.7 является улучшеной версией программы NetworkManager.
Новые особенности включают:
- Поддержка клеточных карт данных
- Несколько активных устройств
- Конфигурация Всей системы
- Интерфейс контроля wpa_supplicant dbus
- Больше Беспроводных/Зашитых методов идентификации
Шаг 1: Установка
NetworkManager доступен в репозитории extra. Для его установки наберите следующую команду:
pacman -S networkmanager libnetworkmanager
Шаг 2: Интеграция в окружение рабочего стола
Gnome
network-manager-applet (ранее известный как gnome-network-manager) доступен в extra-репозитории:
pacman -S network-manager-applet
KDE
KDE4
Плазмойд NetworkManager'а для KDE4 можно найти в репозитории extra, он называется kdeplasma-applets-networkmanagement. Обращаем ваше внимание: данный плазмойд находится на стадии разработки и не является стабильным.
KDE3
Попробуйте использовать knetworkmanager, однако его бинарников больше нет в официальных репозиториях. Найти их можно в AUR.
Xfce
Для Xfce требуется тот же пакет, что и для GNOME:
pacman -S network-manager-applet
Также можно установить плагин xfapplet, который позволит апплетам GNOME отображаться на панели xfce:
pacman -S xfce4-xfapplet-plugin
Если после автоматического запуска гномовских приложений обнаруживается четыре или больше процессе nm-applet, и при этом вы не используете session manager, проделайте следующее:
- Убейте все процессы nm-applet
- Добавьте nm-applet --sm-disable в автозапуск
- Разлогиньтесь из xfce.
- Удалите файл сессии XFCE (он находится в ~/.cache/sessions/)
- Залогиньтесь заново, все должно работать
Fluxbox и другие оконные менеджеры
Для запуска nm-applet вам потребуется hicolor-тема: pacman -S gnome-network-manager hicolor-icon-theme
После необходимой конфигурации вашей системы, можно добавить апплет NetworkManager в автозапуск. Для этого добавьте в список приложений "nm-applet --sm-disable &" (опция "--sm-disable" используется для предотвращения запуска нескольких процессов апплета)
Шаг 3: Настройка
Отключение сетевых интерфейсов
Если вы хотите управлять вашими сетевыми подключениями через NetworkManager вы должны отключить их в /etc/rc.conf. Вы можете использовать знак '!', чтобы отключить интерфейсы, которыми собираетесь управлять, например:
INTERFACES=(lo !eth0 !ath0)
NetworkManager парсит /etc/rc.conf и определяет, статический ip-адрес, или динамический, так что просто поместите туда нужные настройки.
Пример для статического IP:
eth0="eth0 172.19.3.18 netmask 255.255.255.0 broadcast 172.19.3.255"
Пример для динамического IP:
eth0="dhcp"
Изменение имени компьютера в сети
По умолчанию, NetworkManager 0.7 выполняет обратный запрос по ip-адресу, чтобы определить имя хоста. В большинстве случаев это окажется "localhost".
Чтобы этого избежать, можно создать файл /etc/NetworkManager/nm-system-settings.conf и добавить туда следующее:
[main] plugins = keyfile [keyfile] hostname = <нужное имя хоста>
Настройка демонов
Вы должны отключить предыдущий демон управления сетевыми подключениями и добавить демоны hal и networkmanager в следующем порядке:
DAEMONS=( ... !network hal networkmanager ... )
Добавление пользователя в группу network
Add yourself to the network group, replacing USERNAME with the appropriate user name:
# gpasswd -a USERNAME network
Настройка сетевых служб
There are quite a few network services that you will not want running until NetworkManager brings up an interface. Good examples are ntpd and network filesystem mounts of various types. NetworkManager can start these services when you bring an interface up, and stop them when you bring it down.
To use this feature just add scripts to /etc/NetworkManager/dispatcher.d and make them executable for all users; for security, make them owned by root:root and writable only by the owner. The scripts will be run in alphabetical order at interface up time, and in reverse alphabetical order at interface down time. To ensure what order they come up in, simply add an alphabetical character and an underscore at the front of the script name; for example, a_portmap and b_netfs (which ensures that the portmapper is up before NFS mounts are attempted).
I found this naming trick useful for the following items: a_portmap b_netfs c_ntpdate d_ntpd e_cups f_clamav I run a local NTP server, and do not connect my laptop to foreign wireless networks. I also make NFS mounts. There's no point in cups if you're not on the network. Clamav's freshclam signature updater requires networking to connect. I may hack on it some to separate the freshclam service from the clamav on-access scanner so I can keep the on-access scanner running all the time but only run freshclam when the networking is up.
Данный пример позволяет запускать ntpd после поднятия сетевого интерфейса, и останавливать его после отключения последнего интерфейса. Необходимо сохранить как файл /etc/NetworkManager/dispatcher.d/d_ntpd и сделать его исполняемым.
#!/bin/sh
IF=$1 # The interface which is brought up or down
STATUS=$2 # The new state of the interface
case "$STATUS" in
'up') # $IF is up
exec /etc/rc.d/ntpd start
;;
'down') # $IF is down
# Проверяем наличие активных интерфейсов, иначе stop
if [ ! `nm-tool|grep State|cut -f2 -d' '` == "connected" ]; then
exec /etc/rc.d/ntpd stop
fi
;;
esac
Настройка прокси
Network Manager doesn't directly handle proxy settings.
See Proxy settings for more informations.
Проблемы безопасности
Because many Display Managers (including KDM) do not natively support policykit at login, you will run into some permission issues with D-Bus and NetworkManager.
There are several options to resolve this issue (Choose only one).
- Install Consolekit and add the following line to /etc/pam.d/kde
session optional pam_ck_connector.so
- Add the following lines to /etc/dbus-1/system.d/NetworkManager.conf
<policy group="users">
<allow send_destination="org.freedesktop.NetworkManager"/>
<allow send_interface="org.freedesktop.NetworkManager"/>
</policy>
If this does not work, check if there are any policy errors by starting NetworkManager manually:
# kill `pidof NetworkManager` # NetworkManager --no-daemon
- If none of those work
Refer to this forum: https://bbs.archlinux.org/viewtopic.php?id=63576
Возможные проблемы
Проблемы с DHCP
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.
Не определяется 3G модем
Возможно, вашего модема нет в "стандартном" списке NetworkManager. Установите пакет modemmanager, перезапустите networkmanager командой
#/etc/rc.d/networkmanager restart
Затем переподключите модем или перезагрузите компьютер. Должно заработать.
Продвинутые настроки и твики
Checking Whether Networking Is Up In 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
I find 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.
Автоматическое открытие брелка при входе в GNOME
This will prevent nm-applet from asking for your keyring password. Note that this will only work when logging in via GDM.
In /etc/pam.d/gdm, add these lines at the end of the 'auth', 'session' blocks:
auth optional pam_gnome_keyring.so session optional pam_gnome_keyring.so auto_start
In /etc/pam.d/passwd, add this line to the 'password' block:
password optional pam_gnome_keyring.so
Next time you log in, you should get asked if you want the password to be unlocked automatically on login.
See http://live.gnome.org/GnomeKeyring/Pam for reference.
Автоматическое соединение при загрузке системы
Since version 0.7 the NetworkManager is able to connect on boot, before a user has logged in and unlocked the keyring.
First make sure that the keyfile plugin is loaded /etc/NetworkManager/nm-system-settings should look like this:
[main] plugins=keyfile
If this wasn't in the file before, you have to restart nm-system-settings
killall -TERM nm-system-settings
or simply reboot.
Now grant your user the right to modify system-connections with
sudo polkit-auth --grant org.freedesktop.network-manager-settings.system.modify --user "YOURUSERNAME"
And finally in the connection-editor check the Available to all users box.
The connection is now saved in /etc/NetworkManager/system-connections/"CONNECTION NAME".
On reboot, NetworkManager will try to connect to it, when in range.