Mount file share linux

Как в Linux монтировать шару CIFS

Что такое Linux и CIFS простыми словами.

Работа с общими папками Windows происходит с использованием протокола CIFS (SMB). Все примеры в данном руководстве выполняются на Linux Ubuntu и CentOS.

Подготовка

Установка пакетов

Для монтирования общей папки необходимо установить набор утилит для работы с CIFS.

yum install cifs-utils

apt-get install cifs-utils

Сетевые порты

Если мы будем монтировать сетевую папку, сервер которой находится за брандмауэром, необходимо открыть следующие порты:

Синтаксис

* вместо mount.cifs можно написать mount -t cifs.

mount.cifs //192.168.1.1/public /mnt

* простой пример монтирования папки public на сервере 192.168.1.1 в локальный каталог /mnt.

Ручное монтирование

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

mount.cifs //192.168.1.10/share /mnt -o user=dmosk

* в данном примере будет примонтирован каталог share на сервере 192.168.1.10 в локальную папку /mnt под учетной записью dmosk.

То же самое, с использованием домена:

mount.cifs //192.168.1.10/share /mnt -o user=dmosk,domain=dmosk.local

Автоматическое монтирование CIFS через fstab

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

И добавляем в него данные следующего вида:

username=dmosk
password=dPassw0rd
domain=dmosk.local

* в этом примере создана пара логин/пароль — dmosk/dPassw0rd; domain указывать не обязательно, если аутентификация выполняется без него.

Теперь открываем конфигурационный файл fstab:

и добавляем в него следующее:

//192.168.1.10/share /mnt cifs user,rw,credentials=/root/.smbclient 0 0

* в данном примере выполняется монтирование общей папки share на сервере с IP-адресом 192.168.1.10 в каталог /mnt. Параметры для подключения — user: позволяет выполнить монтирование любому пользователю, rw: с правом на чтение и запись, credentials: файл, который мы создали на предыдущем шаге.

Чтобы проверить правильность настроек, вводим следующую команду:

Примеры использования опций

Версии SMB

Если на стороне Windows используется старая или слишком новая версия протокола SMB, при попытке монтирования мы можем получить ошибку mount error(112): Host is down. Чтобы это исправить, указываем версию:

mount.cifs //192.168.1.10/share /mnt/ -o vers=1.0

* монтирование по протоколу SMB1.0

Монтирование от гостевой учетной записи

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

mount.cifs //192.168.1.10/share /mnt -o guest

//192.168.1.10/share /mnt cifs guest 0 0

Права на примонтированные каталоги

При монтировании папки мы можем указать определенные права:

mount.cifs //192.168.1.10/share /mnt -o file_mode=0777,dir_mode=0777

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

mount.cifs //192.168.1.10/share /mnt -o uid=33,gid=33

* чтобы посмотреть идентификаторы пользователя, вводим id -u и id -g .

Источник

Mount SMB Azure file share on Linux

Azure Files is Microsoft’s easy to use cloud file system. Azure file shares can be mounted in Linux distributions using the SMB kernel client.

The recommended way to mount an Azure file share on Linux is using SMB 3.1.1. By default, Azure Files requires encryption in transit, which is supported by SMB 3.0+. Azure Files also supports SMB 2.1, which doesn’t support encryption in transit, but you may not mount Azure file shares with SMB 2.1 from another Azure region or on-premises for security reasons. Unless your application specifically requires SMB 2.1, use SMB 3.1.1.

Читайте также:  Windows 2003 active directory windows 2012
Distribution SMB 3.1.1 SMB 3.0
Linux kernel version
  • Basic 3.1.1 support: 4.17
  • Default mount: 5.0
  • AES-128-GCM encryption: 5.3
  • Basic 3.0 support: 3.12
  • AES-128-CCM encryption: 4.11
Ubuntu AES-128-GCM encryption: 18.04.5 LTS+ AES-128-CCM encryption: 16.04.4 LTS+
Red Hat Enterprise Linux (RHEL)
  • Basic: 8.0+
  • Default mount: 8.2+
  • AES-128-GCM encryption: 8.2+
7.5+
Debian Basic: 10+ AES-128-CCM encryption: 10+
SUSE Linux Enterprise Server AES-128-GCM encryption: 15 SP2+ AES-128-CCM encryption: 12 SP2+

If your Linux distribution isn’t listed in the above table, you can check the Linux kernel version with the uname command:

SMB 2.1 support was added to Linux kernel version 3.7. If you are using a version of the Linux kernel after 3.7, it should support SMB 2.1.

Applies to

File share type SMB NFS
Standard file shares (GPv2), LRS/ZRS
Standard file shares (GPv2), GRS/GZRS
Premium file shares (FileStorage), LRS/ZRS

Prerequisites

Ensure the cifs-utils package is installed.
The cifs-utils package can be installed using the package manager on the Linux distribution of your choice.

On Ubuntu and Debian, use the apt package manager:

On Red Hat Enterprise Linux 8+ use the dnf package manager:

On older versions of Red Hat Enterprise Linux use the yum package manager:

On SUSE Linux Enterprise Server, use the zypper package manager:

On other distributions, use the appropriate package manager or compile from source.

The most recent version of the Azure Command Line Interface (CLI). For more information on how to install the Azure CLI, see Install the Azure CLI and select your operating system. If you prefer to use the Azure PowerShell module in PowerShell 6+, you may, however the instructions in this article are for the Azure CLI.

Ensure port 445 is open: SMB communicates over TCP port 445 — check to see if your firewall is not blocking TCP ports 445 from client machine. Replace and then run the following script:

If the connection was successful, you should see something similar to the following output:

If you are unable to open up port 445 on your corporate network or are blocked from doing so by an ISP, you may use a VPN connection or ExpressRoute to work around port 445. For more information, see Networking considerations for direct Azure file share access.

Mount the Azure file share on-demand with mount

When you mount a file share on a Linux OS, your remote file share is represented as a folder in your local file system. You can mount file shares to anywhere on your system. The following example mounts under the /mount path. You can change this to your preferred path you want by modifying the $mntRoot variable.

Replace , , and with the appropriate information for your environment:

Next, mount the file share using the mount command. In the following example, the $smbPath command is populated using the fully qualified domain name for the storage account’s file endpoint and $storageAccountKey is populated with the storage account key.

Starting in Linux kernel version 5.0, SMB 3.1.1 is the default negotiated protocol. If you’re using a version of the Linux kernel older than 5.0, specify vers=3.1.1 in the mount options list.

You can use uid / gid or dir_mode and file_mode in the mount options for the mount command to set permissions. For more information on how to set permissions, see UNIX numeric notation on Wikipedia.

You can also mount the same Azure file share to multiple mount points if desired. When you are done using the Azure file share, use sudo umount $mntPath to unmount the share.

Automatically mount file shares

When you mount a file share on a Linux OS, your remote file share is represented as a folder in your local file system. You can mount file shares to anywhere on your system. The following example mounts under the /mount path. You can change this to your preferred path you want by modifying the $mntRoot variable.

To mount an Azure file share on Linux, use the storage account name as the username of the file share, and the storage account key as the password. Since the storage account credentials may change over time, you should store the credentials for the storage account separately from the mount configuration.

The following example shows how to create a file to store the credentials. Remember to replace and with the appropriate information for your environment.

To automatically mount a file share, you have a choice between using a static mount via the /etc/fstab utility or using a dynamic mount via the autofs utility.

Static mount with /etc/fstab

Using the earlier environment, create a folder for your storage account/file share under your mount folder. Replace with the appropriate name of your Azure file share.

Finally, create a record in the /etc/fstab file for your Azure file share. In the command below, the default 0755 Linux file and folder permissions are used, which means read, write, and execute for the owner (based on the file/directory Linux owner), read and execute for users in owner group, and read and execute for others on the system. You may wish to set alternate uid and gid or dir_mode and file_mode permissions on mount as desired. For more information on how to set permissions, see UNIX numeric notation on Wikipedia.

Starting in Linux kernel version 5.0, SMB 3.1.1 is the default negotiated protocol. You can specify alternate protocol versions using the vers mount option (protocol versions are 3.1.1 , 3.0 , and 2.1 ).

Dynamically mount with autofs

To dynamically mount a file share with the autofs utility, install it using the package manager on the Linux distribution of your choice.

On Ubuntu and Debian distributions, use the apt package manager:

On Red Hat Enterprise Linux 8+, use the dnf package manager:

On older versions of Red Hat Enterprise Linux, use the yum package manager:

On SUSE Linux Enterprise Server, use the zypper package manager:

Next, update the autofs configuration files.

The final step is to restart the autofs service.

Next steps

See these links for more information about Azure Files:

Источник

Как монтировать общие папки Windows в системах Linux

How to Mount Windows Share on Linux using CIFS

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

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

Общая файловая система Интернета (CIFS) — это сетевой протокол обмена файлами. CIFS является формой SMB.

Установка пакетов утилит CIFS

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

Установка утилит CIFS в Ubuntu и Debian:

Установка утилит CIFS в CentOS и Fedora:

Имя пакета может отличаться в разных дистрибутивах Linux.

Монтирование CIFS Windows Share

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

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

Запустите следующую команду как пользователь root или пользователь с правами sudo для монтирования общего ресурса:

Вам будет предложено ввести пароль:

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

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

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

Пароль также можно указать в командной строке:

Если пользователь находится в рабочей группе или домене Windows, вы можете установить его следующим образом:

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

Файл учетных данных имеет следующий формат:

Файл не должен быть доступен для чтения пользователям. Чтобы установить правильные разрешения и владельца , запустите:

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

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

Используйте dir_mode опцию, чтобы установить разрешение каталога и file_mode установить разрешение файла:

Пользователь по умолчанию и группа собственность могут быть изменены с uid и gid опциями:

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

Авто монтаж

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

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

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

Откройте /etc/fstab файл в текстовом редакторе :

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

Выполните следующую команду для монтирования общего ресурса:

mount Команда, будет читать содержание /etc/fstab и установить долю.

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

Размонтирование Windows Share

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

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

Если в fstab файле CIFS есть запись в файле, удалите ее.

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

Найдя процессы, вы можете остановить их с помощью kill команды и размонтировать общий ресурс.

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

Вывод

В Linux вы можете смонтировать общий доступ к Windows, используя mount команду с cifs параметром.

Источник

Читайте также:  Dns record in linux
Оцените статью