Manjaro Difference between revisions of "Using autofs (automount) with NFS/ru"

Difference between revisions of "Using autofs (automount) with NFS/ru"

From Manjaro
(Created page with "В моем примере это:")
Tags: Mobile web edit Mobile edit
Line 169: Line 169:
''базовый-каталог  имя_общего_файла  опции''.
''базовый-каталог  имя_общего_файла  опции''.


<div lang="en" dir="ltr" class="mw-content-ltr">
В моем примере это:
In my example this is:
</div>


'''/mnt /etc/autofs/auto.shares --time-out=5 --ghost'''
'''/mnt /etc/autofs/auto.shares --time-out=5 --ghost'''

Revision as of 06:03, 17 January 2023

Other languages:
English • ‎Türkçe • ‎русский

Autofs – автомонтирование

Manjaro-logo.png


Autofs

Autofs - это программа, позволяющая монтировать внешние устройства по требованию. Другие способы монтирования могут быть выполнены с помощью ручной команды для временного монтирования или с помощью файла /etc/fstab, если Вы хотите монтировать устройство постоянно.

Autofs можно использовать для монтирования:

  • USB-flash-дисков
  • внешних жестких дисков
  • сетевых устройств хранения данных
  • CD-ROM / DVD / BlueRay и так далее.

Autofs монтирует эти устройства в локальные каталоги. Когда Вы захотите, или программа, которую Вы используете, захочет прочитать с устройства или записать на него, autofs сделает это из этих локальных каталогов. Если Вы много работаете с монтированными системами - Вам определенно понравится данный механизм.

Некоторые люди считают, что поскольку autofs не поддерживается на должном уровне - он не будет существовать долго, но подумайте об этом: зачем поддерживать программу, которая уже делает то, что должна делать?

Другой способ монтирования "на лету" описан на этой странице вики: Fstab - использование автомонтирования SystemD

Установка

На момент написания статьи номер версии autofs был 5.1.3-1. Он может быть установлен из стандартных репозиториев Manjaro с помощью Octopi, Pamac или Pacman. Если Вы хотите использовать autofs с nfs, то Вам понадобится дополнительный пакет - nfs-utils. Поэтому установите и его. В описании он называется: Support programs for Network File Systems

Тестирование монтирования

Перед установкой и настройкой autofs неплохо бы проверить можете ли Вы подключить устройство, которое хотите смонтировать.

Давайте сначала выясним, что Вы хотите монтировать. В пакете nfs-utils есть хорошая команда для этого: showmount:

showmount -e 192.168.1.9

Когда устройство включено - в выводе будет что-то вроде:

Export list for 192.168.1.9: /HDD1 *

На устройстве по адресу 192.168.1.9 находится диск под названием HDD1.

Примечание: Вам необходимо знать IP-адрес устройства чтобы использовать showmount.

Теперь давайте смонтируем его в наш локальный каталог /mnt:

‘’’sudo mount -t nfs 192.168.1.9:/HDD1 /mnt’’’

Введите ls /mnt для просмотра содержимого диска, который вы только что смонтировали. Когда увидите содержимое - монтирование прошло успешно и теперь мы можем продолжить настройку autofs.

Команды терминала

Вы можете использовать следующие команды:

sudo systemctl enable autofs Команда для включения autofs, чтобы её можно было запустить либо вручную, либо при следующей загрузке

sudo systemctl start autofs Команда для ручного запуска autofs

sudo systemctl restart autofs Команда для ручного перезапуска autofs

sudo systemctl stop autofs Команда для ручной остановки autofs

sudo systemctl status autofs Команда для проверки статуса работы autofs

Когда autofs запущен - это вывод команды status:

sudo systemctl status autofs

 ● autofs.service - Automounts filesystems on demand
    Loaded: loaded (/usr/lib/systemd/system/autofs.service; enabled; vendor preset: disabled)
    Active: active (running) since Sat 2017-12-02 07:13:22 CET; 1h 9min ago
   Process: 1069 ExecStart=/usr/bin/automount $OPTIONS --pid-file /run/autofs.pid (code=exited, status=0/SUCCESS)
  Main PID: 1089 (automount)
     Tasks: 5 (limit: 4915)
    CGroup: /system.slice/autofs.service
            └─1089 /usr/bin/automount --pid-file /run/autofs.pid
 Dec 02 07:13:22 Desktop-Jan systemd[1]: Starting Automounts filesystems on demand...
 Dec 02 07:13:22 Desktop-Jan automount[1089]: -
 Dec 02 07:13:22 Desktop-Jan systemd[1]: Started Automounts filesystems on demand.

После остановки он будет таким:

sudo systemctl status autofs

 ● autofs.service - Automounts filesystems on demand
    Loaded: loaded (/usr/lib/systemd/system/autofs.service; enabled; vendor preset: disabled)
    Active: inactive (dead) since Sat 2017-12-02 08:27:27 CET; 1s ago
   Process: 1069 ExecStart=/usr/bin/automount $OPTIONS --pid-file /run/autofs.pid (code=exited, status=0/SUCCESS)
  Main PID: 1089 (code=exited, status=0/SUCCESS)
 Dec 02 07:13:22 Desktop-Jan systemd[1]: Starting Automounts filesystems on demand...
 Dec 02 07:13:22 Desktop-Jan automount[1089]: -
 Dec 02 07:13:22 Desktop-Jan systemd[1]: Started Automounts filesystems on demand.
 Dec 02 08:27:26 Desktop-Jan systemd[1]: Stopping Automounts filesystems on demand...
 Dec 02 08:27:27 Desktop-Jan systemd[1]: Stopped Automounts filesystems on demand.

Конфигурация

После установки нам необходимо настроить несколько файлов в соответствии с нашими потребностями. Эти файлы помещаются в папку: /etc/autofs. На самом деле необходимо 2 файла: auto.master и auto.<любое имя, которое вам нравится>. Поскольку каталог /etc/autofs принадлежит root - Вам нужны права root для записи и/или редактирования этих файлов.

В auto.master мы указываем:

  • базовый каталог, в который мы будем монтировать
  • имя файла, в котором можно настроить монтирование
  • значение таймаута (время, по истечении которого монтирование автоматически отключается, если оно больше не нужно)
  • ghost - опция, которая помещает пустые каталоги в базовый каталог, чтобы после тайм-аута можно было снова смонтировать устройство

Типичная строка в файле auto.master может выглядеть следующим образом:

/mnt /etc/autofs/auto.NAS1 --timeout=10 --ghost

Если у вас есть несколько внешних устройств, которые хотите подключить с помощью autofs, то можно сделать две вещи:

  • прописать дополнительную строку в файле auto.master для каждого устройства. Например:

/mnt /etc/autofs/auto.NAS1 --timeout=10 --ghost

/mnt /etc/autofs/auto.NAS2 --timeout=10 --ghost

и создавать дополнительные файлы конфигурации для каждого устройства, или

  • использовать 1 строку в файле auto.master, используя 1 файл конфигурации для всех устройств, и записать более 1 строки в этом файле конфигурации. Все зависит от вас.

Я пользуюсь этим:

/etc/autofs/auto.master:

/mnt /etc/autofs/auto.shares --time-out=5 --ghost

/etc/autofs/auto.shares:

NAS-Seagate -fstype=nfs,rw,soft,retry=0 Seagate:/shares/Folder1

NAS-WD -fstype=nfs,rw,soft,retry=0 WD:/nfs/Public

Таким образом, у меня есть один главный файл, который одной строкой управляет основой системы, и один файл, управляющий всеми моими ресурсами. Но опять же, это полностью зависит от вас.

Пояснение к auto.master

Этот файл создается при установке пакета autofs. Вам нужно будет отредактировать его под свои нужды. Полный файл при создании выглядит следующим образом:

  1. key [ -mount-options-separated-by-comma ] location
 # For details of the format look at autofs(5).
 #
 #/misc	/etc/auto.misc
 #
 # NOTE: mounts done from a hosts map will be mounted with the
 #	"nosuid" and "nodev" options unless the "suid" and "dev"
 #	options are explicitly given.
 #
 #/net	-hosts
 #
 # Include central master map if it can be found using
 # nsswitch sources.
 #
 # Note that if there are entries for /net or /misc (as
 # above) in the included master map any keys that are the
 # same will not be seen as the first read key seen takes
 # precedence.
 #
 #/net        -hosts           -nosuid
 +auto.master

Добавьте свою строку или строки непосредственно перед последней видимой строкой: +auto.master

После этой строки должна быть пустая строка, иначе конфигурация не примется программой, поэтому установите курсор после +auto.master и нажмите ENTER.

Формат добавляемой строки:

базовый-каталог имя_общего_файла опции.

В моем примере это:

/mnt /etc/autofs/auto.shares --time-out=5 --ghost

NOTE: Make sure the used filename in the auto.master file should be exactly the same as the name of the file you use, including the path.

The base folder can be /. In this case it is written as: /- You use direct addressing now. The address you write in the shares file (see next paragraph) becomes the complete address. When you write the name of a folder in the master file you use indirect addressing: the complete path is now the sum of the path in the master file + the one in the shares file.

Explanation of auto.shares

This file can have any extention name you like. Make it a descriptive one to easily find it, especially when you use more than one. The line or lines in this file are all built according to this template:

name_of_sub-folder options source

(separated with at least one space)

After mounting the external device can be found in the following directory structure:

/base-folder/sub-folder

You define the base folder in the auto.master file (first item in the line) and the sub-folder is defined in the auto.xxxx file (also first item on the line)

My shares are mounted at: /mnt/NAS-WD and /mnt/NAS-Seagate.

/mnt is the base-folder (from auto.master) and both NAS folders are written in the shares file.

Options you can use are plenty. See the man pages for autofs, automount and nfs. The ones I used here work for me. They take care of the following:

  • -fstype=nfs

The used filesystem is nfs (Network File System), a file-system used much in Linux environments.

  • rw

The mount is readable and writable. If you only need read access then use ro (read only)

  • soft

If the server fails an I/O error is given, but the file-manager keeps running. When you use hard instead of soft, it hangs till the connection has been re-established.

  • retry=0

This makes sure that mount stops immediately when the server is not reachable. If not, mount will keep trying for 2 minutes to reach the server and block the program which wants to reach the server.

Remarks

  • It is said that when you make a change in the shares file, the change will be active straight away. When changing the master file you need to restart the autofs.service like this:

sudo systemctl restart autofs It is advisable to also restart after changing the shares file, just to be sure.

  • The permissions of both the master and the share file(s) should be 644. That means Read/Write permission for user, Read for group and Read for others.
  • Test if the system works. First example is the result when nothing is mounted, in the second example you see the result when the NAS-WD is mounted:

$ /etc/autofs > sudo ps -A|grep "nfs\|rpc"

240 ? 00:00:00 rpcbind

 23222 ?       00:00:00 rpciod
 23227 ?       00:00:00 nfsiod 

$ /etc/autofs > cd /mnt/NAS-WD Change directory to the mount

$ /mnt/NAS-WD > sudo ps -A|grep "nfs\|rpc"

240 ? 00:00:00 rpcbind

 23222 ?       00:00:00 rpciod
 23227 ?       00:00:00 nfsiod
 29106 ?       00:00:00 rpc.statd

There are many webpages about autofs, with and without nfs. Just google it and you will find many different ways of setting it up. The way described here works for me and is pretty easy to setup.

Cookies help us deliver our services. By using our services, you agree to our use of cookies.