Linux share folder nfs

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.

Читайте также:  Inactive title windows 10

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.

Источник

10 practical examples to export NFS shares in Linux

Table of Contents

General Syntax to export NFS share

The general syntax which you must use to create a NFS share using /etc/exports will be:

Each line in the file specifies one remote mount point. The first field contains the mount-point directory path, followed optionally by a list of options and/or a list of specific hosts separated by white space. If no specific hosts are specified, the mount point is exported to all hosts.

If you are new to NFS server then I recommend you to first read Overview on NFS and difference between NFSv2 vs NFSv3 and NFSv4

1. Export NFS Share to single host

To export /dump/backups to single client 10.43.138.2 using NFS, I will add below to /etc/exports :

To refresh the share

Since we have not provided any OPTIONS to the NFS share we get this warning. It will work but it is recommended to add atleast » sync » in the OPTIONS section to avoid this warning

So I have updated my /etc/exports

Net refresh the share

Now we don’t get any warning, verify the existing share

2. Export NFS Share to all hosts

To export a NFS share to whole world (this is a dangerous term in production but actually that is what this means). We will use » * » to enable NFS access to the share to all the networks out there which has access to your NFS server

So here we have added no restriction in the exports file for the NFS Share for any of the hosts

3. Export NFS Share to IP Range

Now instead of single host, we will create a exportfs share to be accessed by all the hosts from a network IP range i.e. 10.43.138.1/27

Or alternatively if you don’t have a prefix value, you can provide the netmask value of the subnet

4. Export NFS share to multiple hosts

To export a share to multiple hosts across different network range you must create individual entry of respective hosts.

In this example I am exporting the same path to multiple hosts across different networks.

You can also add them in single line but to make the file content look clean I am using different entries for the same share. To add all these in the single line, the syntax would be:

To use single line share for our last example, we can use:

5. Restrict a NFS share for specified hosts

We can restrict a share in /etc/exports itself by providing only those list of hosts who should be allowed to access the share. But sometimes when you have provided an entire network in the allow list of /etc/exports for example

But you only wish to restrict the share to 10.43.138.2 host. In such case this can be tricky.

With NFSv3 we can use hosts.deny to restrict access to such hosts by using rpcbind, mountd, nfsd, statd, lockd, rquotad to define an access rule but the same is not possible with NFSv4 as it does not use these daemons any more.

To restrict a host with NFSv3 we will add below entry for 10.43.138.2

Now if you try to access the NFS share using this hosts:

But if I try to access the same share using NFSv4

It works. So hosts.deny was unable to block this request.
To overcome this you may rely on firewall to block the respective host from accessing your NFS server

5.1 Restrict NFS shares using iptables

iptables rule to restrict NFS

5.2 Restrict NFS shares using firewalld rich rules

List firewalld rule

However with wildcards we can have more control over the hosts we wish to allow the access for NFS share which we will learn next.

6. How to use wildcard with NFS exports

Machine names may contain the wildcard characters * and ? , or may contain character class lists within [square brackets] . This can be used to make the exports file more compact

Читайте также:  Выход новой версии windows

6.1 Using ? with hostnames

We can use ? wildcard to match a single character in the hostname, for example to match server1 , server2 , serverA , serverX we can use:

If you wish to match for more than one character then you can use ? more than one times. For example to match server12 , server23 , serverAB , serverXY we can use:

6.2 Using square brackets with hostnames

You can use square brackets to define a range of numbers or characters. Below example will match all machines with hostname between server00.example.com to server99.example.com

To map server1 to server5 we can use

To map character with square brackets for example match serverA till serverE , in such case use:

6.3 Using * with hostnames

As you can assume, * means match everything. So assuming you have multiple subdomains under example.com then you can simply use *.example.com to match for all the sub-domains

So this will match

But this will not match

So to match this you must use:

So I hope you got the idea.

7. Export NFS Share as Read Only Mode

To assign a share with read only permission:

Refresh the shares

Verify the exported shares and the options:

8. Export NFS share as Read Write Mode

To export a share with read write permission use:

Refresh and verify the shares and applied options:

Now if someone creates a file in these share on the client nodes:

Create a new file as root user

Verify the permission

As you see the new file is created with nobody permission. By default when NFS share is exported with root_squash permission so any file access and modification from root user will be performed under anonymous account so called nobody user.

Although if you create a file using normal user then the same will be reflected as user and owner of the file:

9. Export a share with NFSv4 only

If you wish create a share which can be accessed over NFSv4 only then you ust modify /etc/nfs.conf

Make sure you disable vers2 and vers3 to only allow connection over NFSv4

Optionally, disable listening for the RPCBIND, MOUNT, and NSM protocol calls, which are not necessary in the NFSv4-only case. Disable related services:

After you configure NFS server, restart the NFS server to activate the changes and enable it start automatically post reboot. You can also check nfs status using systemctl status nfs-server

Use the netstat utility to list services listening on the TCP and UDP protocols:

The following is an example netstat output on an NFSv4-only server; listening for RPCBIND, MOUNT, and NSM is also disabled. Here, nfs is the only listening NFS service:

Next you can create a share using /etc/exports . We don’t need to define any additional permission here:

Now this share will be accessible only over NFSv4.

10. Enable root access on the NFS share

As informed earlier, by default root_squash permission is added to the NFS share which means this permission prevents remote root users from having superuser (root) privileges on remote NFS-mounted volumes. Here, squash literally means to squash the power of the remote root user

So to enable root access we will use no_root_squash which allows root user on the NFS client host to access the NFS-mounted directory with the same rights and privileges that the superuser would normally have.

To disable root squash we use:

To refresh the shares

To learn more about different supported NFS exports options for NFS server and client I would recommend you to read:
Beginners guide to different NFS mount and exports options with examples

Conclusion

In this tutorial I shared multiple examples with different scenarios to export NFS share with and without restrictions. It is important that with NFS we also consider the security of these shares so that it is not accessed by unauthorized users over the network so you must assign the NFS options properly.

Lastly I hope the steps from the article to configure NFS exports share on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

Читайте также:  Удалил службу центр обновления windows

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Как смонтировать общий ресурс NFS в Linux

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

В операционных системах Linux и UNIX вы можете использовать команду mount для монтирования общего каталога NFS в определенной точке монтирования в локальном дереве каталогов.

В этом руководстве мы покажем вам, как вручную и автоматически смонтировать общий ресурс NFS на машинах Linux.

Установка клиентских пакетов NFS

Чтобы смонтировать общий ресурс NFS в системе Linux, сначала необходимо установить клиентский пакет NFS. Название пакета отличается в разных дистрибутивах Linux.

Установка клиента NFS в Ubuntu и Debian:

Установка клиента NFS на CentOS и Fedora:

Монтирование файловых систем NFS вручную

Подключение удаленного общего ресурса NFS аналогично монтированию обычных файловых систем.

Чтобы смонтировать файловую систему NFS в заданной точке монтирования, используйте команду mount в следующей форме:

Выполните следующие действия, чтобы вручную смонтировать удаленный общий ресурс NFS в вашей системе Linux:

Сначала создайте каталог, который будет точкой монтирования для удаленного общего ресурса NFS:

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

Подключите общий ресурс NFS, выполнив следующую команду от имени пользователя root или пользователя с привилегиями sudo :

Где 10.10.0.10 — это IP-адрес сервера NFS, /backup — это каталог, который сервер экспортирует, а /var/backups — локальная точка монтирования.

В случае успеха вывод не производится.

Если вы хотите указать дополнительные параметры монтирования , используйте параметр -o . Несколько вариантов могут быть представлены в виде списка, разделенного запятыми. Чтобы получить список всех параметров монтирования, введите в терминале man mount .

Чтобы убедиться, что удаленный том NFS успешно смонтирован, используйте команду mount или df -h .

После монтирования общего ресурса точка монтирования становится корневым каталогом смонтированной файловой системы.

Когда вы монтируете общий ресурс вручную, подключение общего ресурса NFS не сохраняется после перезагрузки.

Автоматическое монтирование файловых систем NFS с помощью /etc/fstab

Как правило, вы хотите автоматически монтировать удаленный каталог NFS при загрузке системы.

Файл /etc/fstab содержит список записей, определяющих, где, как и какая файловая система будет монтироваться при запуске системы.

Чтобы автоматически монтировать общий ресурс NFS при запуске системы Linux, добавьте строку в файл /etc/fstab . Строка должна включать имя хоста или IP-адрес сервера NFS, экспортированный каталог и точку монтирования на локальном компьютере.

Используйте следующую процедуру для автоматического монтирования общего ресурса NFS в системах Linux:

Настройте точку монтирования для удаленного общего ресурса NFS:

Добавьте в файл следующую строку:

Где 10.10.0.10 — IP-адрес сервера NFS, /backup — это экспортированный каталог, а /var/backups — локальная точка монтирования.

Выполните команду mount в одной из следующих форм, чтобы смонтировать общий ресурс NFS:

Команда mount прочитает содержимое /etc/fstab и смонтирует общий ресурс.

В следующий раз, когда вы перезагрузите систему, общий ресурс NFS будет смонтирован автоматически.

Размонтирование файловых систем NFS

Команда umount отсоединяет (размонтирует) смонтированную файловую систему от дерева каталогов.

Чтобы отсоединить смонтированный общий ресурс NFS, используйте команду umount за которой следует либо каталог, в котором он был смонтирован, либо удаленный общий ресурс:

Если для монтирования NFS есть запись в fstab , удалите ее.

Команда umount не сможет отсоединить общий ресурс, когда смонтированный том используется. Чтобы узнать, какие процессы обращаются к общему ресурсу NFS, используйте команду fuser :

Как только вы найдете процессы, вы можете остановить их с помощью команды kill и отключить общий ресурс NFS.

Если у вас все еще есть проблемы с —lazy ресурса, используйте параметр -l ( —lazy ), который позволяет вам отключать загруженную файловую систему, как только она больше не занята.

Если удаленная система NFS недоступна, используйте параметр -f ( —force ) для принудительного размонтирования.

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

Выводы

Мы показали вам, как подключать и отключать удаленный общий ресурс NFS. Те же команды применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

Оцените статью