Autofs (Русский)
From ArchWiki
Article summary |
---|
Описывает процесс установки и конфигурирования AutoFS, пакета для автоматического монтирования съёмных носителей и сетевых ресурсов. |
Доступные языки |
English |
Español |
Русский |
Contents |
Введение
Этот документ описывают процедуру установки AutoFS, пакета который даёт возможность автоматического монтирования съёмных носителей и сетевых ресурсов при вставке или получении доступа к ним.
Установка
- Установите пакет AutoFS:
# pacman -S autofs
- Запустите модуль autofs4 с правами суперпользователя:
# modprobe autofs4
Конфигурирование
AutoFS использует для конфигурирования шаблоны, расположенные в /etc/autofs
. Основной шаблон называется auto.master
, он может указывать на один или несколько других шаблонов для конкретных типов носителей.
- Откройте
/etc/autofs/auto.master
своим любимым редактором. Вы увидите что-то подобное следующему:
/var/autofs/misc /etc/autofs/auto.misc /var/autofs/net /etc/autofs/auto.net
Первое значение в каждой строке определяет базовый каталог, в который носители будут монтироваться, второе значение - шаблон который будет использован. По умолчанию базовая директория /var/autofs, но вы можете изменить путь на любое другое значение по вашему желанию. Например:
/media/misc /etc/autofs/auto.misc --timeout=5,ghost /media/net /etc/autofs/auto.net --timeout=60,ghost
Дополнительный параметр timeout
устанавливает количество секунд после которых устройство будет размонтировано. Параметр ghost
означает что сконфигурированные ресурсы будут отображаться всегда, а не только тогда, когда они вставлены и доступны. Это полезно тогда, когда вы не хотите запоминать или угадывать имена съёмных носителей и сетевых ресурсов.
Конечные каталоги должны существовать в системе и быть пусты, поскольку их содержимое будет заменено с динамически загружаемого носителя. Однако это не критично, если вы случайно монтировали носитель в непустую директорию, просто измените путь в auto.master и перезапустите AutoFS чтобы вернуть исходное содержимое.
- Откройте файл
/etc/nsswitch.conf
и добавьте запись для автоматического монтирования:
automount: files
Съёмные носители
- Откройте
/etc/autofs/auto.misc
и добавьте, удалите или измените всевозможные устройства. Например:
#kernel -ro ftp.kernel.org:/pub/linux #boot -fstype=ext2 :/dev/hda1 usbstick -fstype=auto,async,nodev,nosuid,umask=000 :/dev/sdb1 cdrom -fstype=iso9660,ro :/dev/cdrom #floppy -fstype=auto :/dev/fd0
Если у вас комбинированный CD/DVD-привод вы можете изменить тип в строке cdrom на "-fstype=auto" для авто-определения типа носителя.
Монтирование NFS
AutoFS предоставляет новый способ автоматического обнаружения и монтирования NFS-ресурсов на удалённых серверах (шаблон конфигурирования сетевых ресурсов /etc/autofs/auto.net
был удалён в autofs5). Чтобы включить автомагическое обнаружение и монтирование сетевых ресурсов со всех доступных серверов без необходимости дополнительного конфигурирования, вам необходимо добавить следующее в файл /etc/autofs/auto.master
:
/net -hosts --timeout=60
Каждое имя хоста должно быть разрешено, например, любой IP-адрес в /etc/hosts
или заданный через DNS.
К примеру, есть удалённый сервер fileserver с ресурсом NFS, который называется /home/share, вы можете получить доступ к ресурсу просто набрав:
# cd /net/fileserver/home/share
/etc/conf.d/autofs
in order to start the AutoFS daemon.The -hosts
option uses a similar mechanism as the showmount command to detect remote shares. You can see the exported shares by typing:
# showmount <servername> -e
Замените <servername> на имя ващего собственного сервера.
Samba
Сборка пакета в Arch не содержит каких-либо samba или cifs шаблонов/скриптов (23.07.2009), но следующее должно работать для отдельных ресурсов:
добавьте следующее в /etc/autofs/auto.master
/media/[my_server] /etc/autofs/auto.[my_server]
а затем создайте файл /etc/autofs/auto.[my_server]
[my_share] -fstype=cifs,[other_options] ://[my_server_ip]/[my_share]
FTP и SSH (через Fuse)
Доступ к удалённым FTP- и SSH-серверам может быть легко получен с AutoFS, используя Fuse, часть виртуальной файловой системы.
Удёлнные FTP
Во-первых, установите пакет curlftpfs из репозитория Community:
# pacman -S curlftpfs
Загрузите модуль Fuse:
# modprobe fuse
Добавьте fuse массив modules в /etc/rc.conf
для загрузки его при каждом запуске компьютера.
Далее, добавьте новую запись для FTP-серверов в /etc/autofs/auto.master
:
/media/ftp /etc/autofs/auto.ftp --timeout=60,ghost
Создайте файл /etc/autofs/auto.ftp
и добавьте сервер в формате ftp://myuser:mypassword@host:port/path
:
servername -fstype=curl,allow_other :ftp\://myuser\:mypassword\@remoteserver
Note: Your passwords are plainly visible for anyone that can run df (only for mounted servers) or view the file /etc/autofs/auto.ftp
.
If you want slightly more security you can create the file ~root/.netrc
and add the passwords there.
Passwords are still plain text, but you can have mode 600, and df command will not show them (mounted or not).
This method is also less sensitive to special characters (that else must be escaped) in the passwords. The format is:
machine remoteserver login myuser password mypassword
The line in /etc/autofs/auto.ftp
looks like this without user and password:
servername -fstype=curl,allow_other :ftp\://remoteserver
Create the file /sbin/mount.curl
with this code:
#! /bin/sh curlftpfs $1 $2 -o $4,disable_eprt
Create the file /sbin/umount.curl
with this code:
#! /bin/sh fusermount -u $1
Set the permissions for both files:
# chmod 755 /sbin/mount.curl # chmod 755 /sbin/umount.curl
After a restart your new FTP server should be accessible through /media/ftp/servername
Remote SSH
These are basic instructions to access a remote filesystem over SSH with AutoFS.
Install the sshfs package from the Extra repository:
# pacman -S sshfs
Load the Fuse module:
# modprobe fuse
Add fuse to the modules array in /etc/rc.conf
to load it on each system boot:
Install OpenSSH:
# pacman -S openssh
Generate an SSH keypair:
# ssh-keygen -t dsa
When the generator ask for a passphrase, just press enter. Using SSH keys without a passphrase is less secure, yet running AutoFS together with passphrases poses some additional difficulties which are not (yet) covered in this article.
Next, copy the public key to the remote SSH server:
# ssh-copy-id -i ~/.ssh/id_dsa.pub username@remotehost
Copy the private key to the root's home directory so that AutoFS can find it:
# sudo cp ~/.ssh/id_dsa /root/.ssh/id_dsa
The above is a workaround since AutoFS runs as root and has no default access to the user's home directory containing the private key.
See that you can login to the remote server without entering a password:
# ssh username@remotehost
Create a new entry for SSH servers in /etc/autofs/auto.master
:
/media/ssh /etc/autofs/auto.ssh --timeout=60,ghost
Create the file /etc/autofs/auto.ssh
and add an SSH server:
servername -fstype=fuse,rw,nodev,nonempty,allow_other,max_read=65536 :sshfs\#username@host\:/
After a restart your SSH server should be accessible through /media/ssh/servername
Starting AutoFS
- When you are done configuring, launch the AutoFS daemon as root:
# /etc/rc.d/autofs start
To start the daemon on boot you can add autofs
to the DAEMONS array in /etc/rc.conf, and autofs4
to the modules array in the same file.
If you change the auto.master template while AutoFS is running, you will have to restart the daemon for the changes to become effective:
# /etc/rc.d/autofs restart
Devices are now automatically mounted when they are accessed, they will remain mounted as long as you access them.
Troubleshooting and tweaks
This section contains a few solutions for common issues with AutoFS.
Optional parameters
You can set parameters like timeout
systemwide for all AutoFS media in /etc/conf.d/autofs
:
- Open the
/etc/conf.d/autofs
file and edit the daemonoptions line:
daemonoptions='--timeout=5'
- To enable logging (default is no logging at all), add
--verbose
to the daemonoptions line in/etc/conf.d/autofs
, e.g.:
daemonoptions='--verbose --timeout=5'
After restarting the autofs daemon, verbose output is visible in /var/log/daemon.log.
Identify multiple devices
If you use multiple usb drives/sticks and want to easily tell them apart, you can use AutoFS to set up the mount points and udev to create distinct names for your usb drives. See Using udev to map multiple entries to a device for instructions on setting up udev rules.
AutoFS permissions
If AutoFS isn't working for you, make sure that the permissions of the templates files are correct, otherwise AutoFS will not start. This may happen if you backed up your configuration files in a manner which did not preserve file modes. Here are what the modes should be on the configuration files:
- 0644 - /etc/autofs/auto.master
- 0644 - /etc/autofs/auto.media
- 0644 - /etc/autofs/auto.misc
- 0644 - /etc/conf.d/autofs
In general, scripts (like previous auto.net) should have executable (chown a+x filename) bits set and lists of mounts shouldn't.
If you are getting errors in /var/log/daemon.log similar to this, you have a permissions problem:
May 7 19:44:16 peterix automount[15218]: lookup(program): lookup for petr failed May 7 19:44:16 peterix automount[15218]: failed to mount /media/cifs/petr
External links and resources
- The original information on this page is based on this topic: http://bbs.archlinux.org/viewtopic.php?t=7630, with additional information found on this page: http://libranet.com/support/2.8/0381
- FTP and SFTP usage with AutoFS is based on this Gentoo Wiki article: http://en.gentoo-wiki.com/wiki/Mounting_SFTP_and_FTP_shares
- More information on SSH can be found on the SSH and Using SSH Keys pages of this wiki.
Alternatives to AutoFS
- Thunar Volume Manager is an automount system for users of the Thunar file manager.
- Pcmanfm-fuse is a lightweight file manager with built-in support for accessing remote shares: http://aur.archlinux.org/packages.php?ID=22992