Меню Рубрики

Mount linux nfs share

How to Mount an NFS Share in Linux

Posted Aug 23, 2019

Network File System (NFS) is a distributed file system protocol that allows you to share remote directories over a network. With NFS, you can mount remote directories on your system and work with the remote files as if they were local files.

On Linux and UNIX operating systems, you can use the mount command to mount a shared NFS directory on a particular mount point in the local directory tree.

In this tutorial, we will show you how to manually and automatically mount an NFS share on Linux machines.

Installing NFS Client Packages #

To mount an NFS share on a Linux system first you’ll need to install the NFS client package. The package name differs between Linux distributions.

Installing NFS client on Ubuntu and Debian:

Installing NFS client on CentOS and Fedora:

Manually Mounting an NFS File Systems #

Mounting a remote NFS share is the same as mounting regular file systems.

To mount an NFS file system on a given mount point, use the mount command in the following form:

Use the steps below to manually mount a remote NFS share on your Linux system:

First, create a directory to serve as the mount point for the remote NFS share:

Mount point is a directory on the local machine where the NFS share is to be mounted.

Mount the NFS share by running the following command as root or user with sudo privileges:

Where 10.10.0.10 is the IP address of the NFS server, /backup is the directory that the server is exporting and /var/backups is the local mount point.

On success, no output is produced.

If you want to specify additional mount options , use the -o option. Multiple options can be provided as a comma-separated list. To get a list of all mount options type man mount in your terminal.

To verify that the remote NFS volume is successfully mounted use either the mount or df -h command.

Once the share is mounted, the mount point becomes the root directory of the mounted file system.

When you are manually mounting the share, the NFS share mount does not persist after a reboot.

Automatically Mounting NFS File Systems with /etc/fstab #

Generally, you will want to mount the remote NFS directory automatically when the system boots.

The /etc/fstab file contains a list of entries that define where how and what filesystem will be mounted on system startup.

To automatically mount an NFS share when your Linux system starts up add a line to the /etc/fstab file. The line must include the hostname or the IP address of the NFS server, the exported directory, and the mount point on the local machine.

Use the following procedure to automatically mount an NFS share on Linux systems:

Set up a mount point for the remote NFS share:

Open the /etc/fstab file with your text editor :

Add the following line to the file:

Where 10.10.0.10 the NFS server IP address, /backup is the exported directory and /var/backups is the local mount point.

Run the mount command in one of the following forms to mount the NFS share:

The mount command, will read the content of the /etc/fstab and mount the share.

Next time you reboot the system the NFS share will be mounted automatically.

Unmounting NFS File Systems #

The umount command detaches (unmounts) the mounted file system from the directory tree.

To detach a mounted NFS share, use the umount command followed by either the directory where it has been mounted or remote share:

If the NFS mount have an entry in the fstab file, remove it.

The umount command will fail to detach the share when the mounted volume is in use. To find out which processes are accessing the NFS share, use the fuser command:

Once you find the processes you can stop them with the kill command and unmount the NFS share.

If you still have problems unmounting the share use the -l ( —lazy ) option which allows you to unmount a busy file system as soon as it is not busy anymore.

If the remote NFS system is unreachable, use the -f ( —force ) option to force an unmount.

Generally not a good idea to use the force option as it may corrupt the data on the file system.

Conclusion #

We have shown you how to mount and unmount a remote NFS share. The same commands apply for any Linux distribution, including Ubuntu, CentOS, RHEL, Debian and Linux Mint.

Feel free to leave a comment if you have any questions.

Источник

How To Mount NFS Share In Linux and Windows?

Network File System or NFS is a network-based filesystem protocol which is mainly used to share files and folders over the network. NFS is a UNIX based technology but can be used by most of the operating systems like Linux, Ubuntu, Debian, Kali, Mint, Fedora, CentOS, RedHat and Windows operating systems Windows 7, Windows 8, Windows 10, Windows Server 2008, Windows Server 2012, Windows Server 2016.

Install NFS Server

NFS packages mainly divided into two parts. First is the server side packages which will install related kernel modules and server tools.

Ubuntu, Debian, Mint, Kali Client Packages

Fedora, CentOS, Fedora Client Packages

Ubuntu, Debian, Mint, Kali Server Packages

After the installation is complete the nfs-server service will be also created automatically.

Fedora, CentOS, Fedora Server Packages

Check NFS Service Status

As the NFS shares will be served over nfs-server we need to the if it is working. We will use systemctl status command with the nfs-server service name.

Check NfS Service Status

We can see that the service is active and working properly.

Start NFS Service

If the service is not started or stopped in any way we need to start the nfs-server service. We will use systemctl start command with the nfs-server service name like below.

Create NFS Share

NFS main configuration is stored in the /etc/exports file. Each share is created line by line. For example, if we want to share /mnt with the IP address 192.168.10.10 we will use the following configuration.

But generally, we share the files and folders with everyone who has access to the NFS server. We can use the following configuration to share everyone.

Enable Exports

After creating the share configuration we need to refresh the NFS table where the shares are stored. We can simply use exportfs command with the -a option which will add current configuration to the NFS table.

Mount NFS Share For Linux

We can use mount command in order to mount NFS share. We will specify the filesystem type as nfs to the mount command with the -t option like below. The server IP address is 192.168.142.144 and share is /mnt . We will mount to the /home/ismail/poftut1 .

List NFS Mounts

After mounting the NFS share we can check it by listing the NFS mount. We will use mount command and filter NFS shares with the grep command like below.

List NFS Mounts

Unmount NFS Share For Linux

We can unmount already mounted NFS shares with the umount command. We will just specify the mount path to the umount command with the sudo command like below.

Mount NFS Share For Windows

First, we will enable NFS modules or features on Windows operating systems. Open Start > Control Panel > Programs. Select Turn Windows Features on or off. Select Services for NFS. Click OK.

We can mount NFS shares in Windows operating systems too. We will use mount command. We will also provide nolock option and other parameters like remote NFS server IP address and local drive which is Z in this case.

Alternatively, we can use net use command which can also mount NFS shares. We will provide the partition name which is z and remote NFS server.

Источник

Установка

Для установки и сервера, и клиента необходимы одни и те же пакеты nfs-kernel-server и nfs-common

Настройка сервера

Все настройки сервера хранятся в файле /etc/exports . Открываем его на редактирование

и добавляем в конец файла строки вида (строк может быть произвольное количество):

/data –путь к папке, для которой раздается доступ;

192.168.1.1 –IP-адрес, которому раздается доступ к папке(можно указать всю сеть, тогда запись примет вид 192.168.1.0/24)

(rw,no_root_squash,sync) –набор опций, опции могут быть:

rw –чтение запись(может принимать значение ro-только чтение);

no_root_squash –по умолчанию пользователь root на клиентской машине не будет иметь доступа к разделяемой директории сервера. Этой опцией мы снимаем это ограничение. В целях безопасности этого лучше не делать;

nohide — NFS автоматически не показывает нелокальные ресурсы (например, примонтированые с помощью mount –bind), эта опция включает отображение таких ресурсов;

sync – синхронный режим доступа(может принимать обратное значение- async). sync (async) — указывает, что сервер должен отвечать на запросы только после записи на диск изменений, выполненных этими запросами. Опция async указывает серверу не ждать записи информации на диск, что повышает производительность, но понижает надежность, т.к. в случае обрыва соединения или отказа оборудования возможна потеря данных;

noaccess – запрещает доступ к указанной директории. Может быть полезной, если перед этим вы задали доступ всем пользователям сети к определенной директории, и теперь хотите ограничить доступ в поддиректории лишь некоторым пользователям.

Необходимо добавить описание опций.

all_squash– подразумевает, что все подключения будут выполнятся от анонимного пользователя

subtree_check (no_subtree_check)- в некоторых случаях приходится экспортировать не весь раздел, а лишь его часть. При этом сервер NFS должен выполнять дополнительную проверку обращений клиентов, чтобы убедиться в том, что они предпринимают попытку доступа лишь к файлам, находящимся в соответствующих подкаталогах. Такой контроль поддерева (subtree checks) несколько замедляет взаимодействие с клиентами, но если отказаться от него, могут возникнуть проблемы с безопасностью системы. Отменить контроль поддерева можно с помощью опции no_subtree_check. Опция subtree_check, включающая такой контроль, предполагается по умолчанию. Контроль поддерева можно не выполнять в том случае, если экспортируемый каталог совпадает с разделом диска;

anonuid=1000– привязывает анонимного пользователя к «местному» пользователю;

anongid=1000– привязывает анонимного пользователя к группе «местного» пользователя.

В последствии после внесения изменений в файл /etc/exports не обязательно перезапускать сервер, достаточно выполнить:

Настройка клиента

Для монтирования сетевой папки необходимо создать папку на локальном компьютере:

Монтирование вручную

Для монтирования папки вручную необходимо выполнить в терминале команду:

Монтирование с записью в fstab

Для большего удобства можно добавить запись с сетевой папкой в fstab. Целесообразно создать точку монтирования сетевой папки в /media, потому что каталоги, созданные там, будут отображаться в Nautilus в левой колонке, монтировать их можно будет одним кликом.

В файл /etc/fstab добавляем подобную запись:

опция «noauto» запрещает автоматическое монтирование сетевого диска при старте системы.

Проблемы

Использование на ноутбуке

При монтировании удаленных папок NFS посредством fstab, в ситуации, когда сеть с сервером будет не доступна, ноутбук невозможно выключить или отправить в спящий режим. Для использования удаленных папок NFS на ноутбуке лучше воспользоваться монтированием при помощи autofs

Монтирование с помощью autofs

Данный способ монтирования позволяет автоматически монтировать папку после обращения к ней в наутилусе (к примеру, через закладки) или в терминале:

и автоматически отмонтировать при отсутствии активности.

Установка

Для реализации данного способа необходимо доустановить пакет autofs :

Настройка

Для настройки autofs в файле /etc/auto.master необходимо добавить строку

Здесь –timeout=60 указывает отмонтировать раздел при отсутствии активности на нём более чем 60 секунд. Создаем в корне файловой системы папку /nfs :

В файле /etc/auto.nfs добавляем строку

-rw,soft,intr,rsize=8192,wsize=8192 – параметры монтирования;

server – папка, которая будет создаваться в каталоге /nfs при монтировании удаленных папок;

192.168.1.2:/path_to_share– IP-адрес и общая папка сервера.

Перезапускаем службу autofs :

Проблемы

Недоступность удаленного сервера

Если сеть с сервером NFS недоступна, возможна большая задержка (по умолчанию 3 минуты) при открытии nautilus, в закладках которого находится примонтированная удаленная папка NFS.
Для решения этой проблемы необходимо уменьшить время ожидания монтирования autofs, для этого в файле /etc/default/autofs необходимо раскомментировать или добавить следующие строки:

#время ожидания ответа от mount

#время ожидания при неудачной попытке монтирования

После этого autofs будет пытаться примонтировать удаленную папку только 10 секунд.

Использование

Проблемы

Проблемы с гибернацией или выключением

После настройки автомонтирования сетевых папок NFS могут обнаружится некотрые проблемы с выключением или гибернацией системы. Чаще всего это проявляется как прерывающаяся гибернация (компьютер начинает уходить в гибернацию, гаснет экран, после чего экран опять загорается и работа продолжается, так же в этих случаях возможны проблемы с выключением и перезагрузкой системы. При последующих попытках отправить компьютер в гибернацию на черном экране вверрху можно наблюдать строку типа:

Для диагностирования смотрим лог dmesg, возможный вывод:

Пакет, являющийся причиной зависания указан в начале строки, следующей после сообщения об ошибке.

Причина №1: пакет NFS

Причиной данной проблемы является скрипт прерывания работы NetworkManager, необходимо запретить его выполнение переименовав его:

Причина №2: пакет updatedb.mloc

updatedb является частью пакета mlocate— удобного пакета для быстрого поиска файлов по системе. К сожалению, версия 0.23.1-1ubuntu2 1) , находящаяся в репозиториях Ubuntu содержит баг, при котором возникает ситуация, когда компьютер не может выключиться или отправиться в гибернацию, когда сервер NFS выключен. Для решения данной проблемы необходимо установить пакет версии 0.23.1-1 из репозитория debian-sid:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Криптопровайдер на mac os
  • Криптопро csp для mac os x
  • Криптоарм для mac os
  • Краткая характеристика mac os
  • Кракозябры в mail mac os