- Mount SMB Azure file share on Linux
- Applies to
- Prerequisites
- Mount the Azure file share on-demand with mount
- Automatically mount file shares
- Static mount with /etc/fstab
- Dynamically mount with autofs
- Next steps
- Linux smb file share
- How to mount SAMBA share (SMBFS) in Linux
- Listing SMB Share Folder
- Mounting SMB Share on Local Directory
- Mounting SMB Share with Mount Command
- Mounting CIFS (Common Internet File System)
- Mount with Password
- Permanent Mount
- Secure Way To Mount Share Permanently
- You may also like
- How to Mount Samba Share on CentOS/Fedora/Redhat?
- How to Mount Samba Share on Ubuntu and Debian System?
- How To Configure Samba Server In Linux
- Some Basic Linux Commands Interview Questions
- About the author
- Santosh Prasad
- 9 Comments
- Файловый сервер SAMBA на базе Linux CentOS 7
- Установка CentOS 7
- Получение ip адреса по DHCP
- Установка на VM агентов для взаимодействия с хост сервером
- Установка обновлений
- Midnight Commander
- Настройка сети
- Настройка FQDN
- SELINUX
- SAMBA
- firewallD
- Общий ресурс с анонимным доступом
- Бантики
- Подключение диска
- Подключение образа диска
- Подключение RAM диска
- Удаление старых файлов
- Ограничение доступа к SAMBA по ip адресам
- Аутентификация и авторизация пользователей
- Интеграция с Active Directory
- winbind
- Добавление хоста в AD
- Что делает утилита authconfig-tui?
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.
Distribution | SMB 3.1.1 | SMB 3.0 |
---|---|---|
Linux kernel version |
|
|
Ubuntu | AES-128-GCM encryption: 18.04.5 LTS+ | AES-128-CCM encryption: 16.04.4 LTS+ |
Red Hat Enterprise Linux (RHEL) |
| 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:
Источник
Linux smb file share
Linux (UNIX) machines can also browse and mount SMB shares. Note that this can be done whether the server is a Windows machine or a Samba server!
An SMB client program for UNIX machines is included with the Samba distribution. It provides an ftp-like interface on the command line. You can use this utility to transfer files between a Windows ‘server’ and a Linux client.
Most Linux distributions also now include the useful smbfs package, which allows one to mount and umount SMB shares. More on smbfs below.
To see which shares are available on a given host, run:
where ‘host’ is the name of the machine that you wish to view. this will return a list of ‘service’ names — that is, names of drives or printers that it can share with you. Unless the SMB server has no security configured, it will ask you for a password. Get it the password for the ‘guest’ account or for your personal account on that machine.
The output of this command should look something like this:
The browse list shows other SMB servers with resources to share on the network.
To use the client, run:
where ‘service’ is a machine and share name. For example, if you are trying to reach a directory that has been shared as ‘public’ on a machine called zimmerman, the service would be called \\zimmerman\public. However, due to shell restrictions, you will need to escape the backslashes, so you end up with something like this:
where ‘mypasswd’ is the literal string of your password.
You will get the smbclient prompt:
Type ‘h’ to get help using smbclient:
If you can use ftp, you shouldn’t need the man pages for smbclient.
Although you can use smbclient for testing, you will soon tire of it for real work. For that you will probably want to use the smbfs package. Smbfs comes with two simple utilties, smbmount and smbumount. They work just like mount and umount for SMB shares.
One important thing to note: You must have smbfs support compiled into your kernel to use these utilities!
The following shows a typical use of smbmount to mount an SMB share called «customers» from a machine called «samba1»:
Issuing a mount command will now show the share mounted, just as if it were an NFS export:
Please see the manual pages for smbmount and smbumount for details on the above operation.
Источник
How to mount SAMBA share (SMBFS) in Linux
Linux system can also browse and mount SMB shares. In this article I am going to explain how you can mount SAMBA file system (SMBFS) permanently in Linux. Please note that this can be done whether the server is a Windows machine or a Samba server.
Listing SMB Share Folder
-L : Listing of SMB share
Mounting SMB Share on Local Directory
Mounting SMB Share with Mount Command
Mounting CIFS (Common Internet File System)
Advanced SMB file system implementation which support RAP (Remote Access Protocol).
Mount with Password
Permanent Mount
For permanent mount you will need to edit /etc/fstab file like below.
Save and close the file.
Now run the below command to verify.
For Domain User
Above prasad is a domain user.
Secure Way To Mount Share Permanently
As you know that /etc/fstab file is visible for all logged in user, So mentioning user and password in /etc/fstab is not a good idea. To overcome this issue just create a credential file in user’s home directory and point that file in /etc/fstab like below.
Save and close file.
Now edit the /etc/fstab file like below.
Save and close file.
Now verify by executing below command.
I hope this article will help to mount SMB share on Linux system. If you have any queries and problem please comment in comment section.
If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com . To become an author at Look Linux Submit Article . Stay connected to Facebook .
You may also like
How to Mount Samba Share on CentOS/Fedora/Redhat?
How to Mount Samba Share on Ubuntu and Debian System?
How To Configure Samba Server In Linux
Some Basic Linux Commands Interview Questions
About the author
Santosh Prasad
Hi! I’m Santosh and I’m here to post some cool article for you. If you have any query and suggestion please comment in comment section.
9 Comments
Pretty! This was an incredibly wonderful article. Thank you for providing these details.
I’m very happy to discover this web site. I want to to thank you for ones time due to
this fantastic read!! I definitely enjoyed every part of it and
I have you bookmarked to check out new stuff on your web site.
I savour, cause I found exactly what I wass having
a look for. You have ended myy 4 dday lengthy hunt! God Bles you man. Have a
great day
You missed the comma between the credentials and the next option ‘rw’ — cheers
each time i used to read smaller posts which as well clear their motive, and that is also happening with this piece of writing which I am reading at this
time.
thanks for the information. it seems that from all the postings i have seen, it seems to me that the simpler the better. Your suggestion above worked but not completely as you have shown. In lieu of “smbfs” i used cifs as the file system type, and it worked like a charm.
Thanks for the article. There is an error in your mount -t cifs command. The IP address has to have // in front and no colon. “//127.0.0.1/folder”
You’ve made some decent points there. I looked on the net for additional information about the issue and
found most individuals will go along with your views on this web site.
I have a possible correction for Debian users.
To mount shared folder with mount command you on’t use:
mount -t cifs //ip.of.samba.server:/……
That ‘:’ should not be there. You’ll get an error.
Источник
Файловый сервер SAMBA на базе Linux CentOS 7
Привет Хабр!
После активности шифровальщика Petya 27.06.2017, я отключил SMB1 он же CIFS, и получил производственное оборудование и сетевые МФУ которые не умеют работать на «новых» версиях SMB протокола.
Как тогда получать данные с «старых» устройств? Как показала практика, отдельная «машина» с Windows не выход, во время атаки кроме доменных «машин» пострадали также не включенные в домен, по этому, а также по лицензионным соображениям я решил использовать Linux.
Под катом находится пошаговая инструкция по установке и настройке файлового сервера SAMBA на базе CentOS 7:
— Анонимный доступ
— Аутентификация и авторизация
— Интеграция с Active Directory
Установка CentOS 7
Сервера работают под управлением VMware ESXi, и по этому я установил CentOS 7 1611 на VM, выделив 1 CPU, 1GB RAM и 3GB HDD.
LVM я не использую, SWAP раздел не создаю, на загрузочный раздел выделяю 500MB, а все остальное отдаю под корень файловой системы. В качестве файловой системы использую ext4.
Процесс установки описывать я не буду, даже если вы этого никогда не делали, это не сложно, у вас все получится. Предполагаю что вы уже все установили, тогда можно приступать.
Если вы новичок в линукс, делайте копии оригинальных файлов с конфигами, используйте команду cp.
Получение ip адреса по DHCP
Если по какой-то причине в сети нету DHCP сервера, вам стоит его поднять. Работать с большим количеством VM без DHCP не удобно.
Для принудительного обновления или получения ip адреса выполните команду
Показать ip адрес
CentOS 7 использует пакетный менеджер YUM. Шпаргалка по yum находится тут.
Если выход в интернет организован через прокси сервер, добавьте адрес прокси в файл конфигурации /etc/yum.conf, используйте редактор vi или следующую команду
В случае использования логина и пароля для доступа к прокси серверу, добавьте следующие параметры:
Установка на VM агентов для взаимодействия с хост сервером
Для VMware ESXi необходимо установить open-vm-tools
Для Hyper-V, hyperv-daemons
Установка обновлений
Очень важно установить все доступные обновления
Midnight Commander
Редактировать файлы без нормального редактора очень не удобно, и я предлагаю использовать mc и mcedit
Настройка сети
Для настройки статического ip адреса и имени хоста можно использовать утилиту nmtui
В командной строке список сетевых адаптеров можно получить командой
Статический ip и gateway задается следующей командой, где «ens192» это имя сетевого адаптера
Настройка FQDN
Пусть полное имя хоста будет ls01.fqdn.com, выполняем команду
Перезагружаем службу имен
Проверить результат можно следующими командами
Если протокол ipv6 не используется, логично его отключить, для этого нужно добавить два параметра в файл /etc/sysctl.conf, выполните следующие команды или используйте редактор mcedit
Перезагрузите службу сети
SELINUX
На данном этапе службу SELINUX необходимо отключить, проверить статус службы SELINUX можно командой
Измените значение SELINUX в файле /etc/selinux/config на SELINUX=disabled затем перезагрузите сервер.
Вернусь к SELINUX в конце статьи.
SAMBA
Добавление службы в автоматический запуск
Запуск службы и проверка состояния
firewallD
По умолчанию CentOS 7 использует брандмауэр firewallD, состояние службы можно узнать командой
Для получения списка правил и сервисов используйте
Обратите внимание на список сервисов, если вы отключили протокол ipv6, логично также поступить и с dhcpv6-client
Создаем правило для SAMBA и перезагружаем
Общий ресурс с анонимным доступом
Создаем папку для ресурса /samba/guest
Меняем владельца и назначаем права
Редактируем файл конфигурации SAMBA /etc/samba/smb.conf
Меняем содержание оригинального файла на следующее
[global]
workgroup = WORKGROUP
security = user
map to guest = bad user
min protocol = NT1
[guest]
path = /samba/guest
guest ok = Yes
writable = Yes
На всякий случай я указал минимальную версию протокола SMB=NT1. Если вы укажите SMB2 или SMB3, клиенты с Windows XP и ниже не смогут получить доступ к ресурсам.
Проверка параметров и перезагрузка службы
Поздравляю вас, достигнут первый уровень посвящения. Общий ресурс с анонимным доступом настроен, будет работать долго и надежно. Но можно и нужно настроить еще несколько вещей.
Бантики
[global]
load printers = no
show add printer wizard = no
printcap name = /dev/null
disable spoolss = yes
Конфигурация SAMBA находиться в каталоге /etc/samba, а логи в каталоге /var/log/samba
Мне удобней все инструменты держать по рукой, по этому я монтирую необходимые мне каталоги в /samba
Создаем каталоги, в которые будет все монтироваться
Редактируем конфиг файл /etc/fstab, я предполагаю что вы знаете за что отвечает fstab.
Добавляем следующие строки
/etc/samba /samba/smbconf none bind 0 0
/var/log/samba /samba/smblogs none bind 0 0
Монтируем без перезагрузки
Подключение диска
Держать ресурс с общим доступом на системном диске без квоты, не лучший выбор. С квотами я решил не связываться, мне проще подключить отдельный «физический» диск.
Для получения списка устройств можно использовать команду lsblk
Создание таблицы разделов на диске /dev/sdb
Подробную информация про gpt можно прочитать тут
Создание раздела на весь диск sdb, в лучших традициях жанра я решил сделать отступ 1MiB в начале диска.
Создаем файловую систему ext4
Добавляем еще одну строку
/dev/sdb1 /samba/guest ext4 defaults 0 0
Подключение образа диска
Если вам не нужны большие объемы, и достаточно ресурса размером ххх мб, можно подключить образ диска из файла.
Создаем каталог для хранения образов
Создаем файл образа размером 100 мб
Про команду dd много интересного можно прочитать тут
В варианте с образом я решил не создавать таблицу разделов, просто создаем файловую систему ext4.
Конфиг для монтирования образа
/samba/smbimg/100M.img /samba/guest ext4 defaults 0 0
Подключение RAM диска
Для временных ресурсов где не нужен большой объем, как мне кажется RAM диск это наилучший вариант, очень быстро и просто настраивается, а скорость работы поражает воображение.
Конфиг для RAM диска
none /samba/guest tmpfs defaults,size=100M 0 0
Удаление старых файлов
В случае «файлопомойки» ресурсы нужно как-то освобождать, для этого можно использовать планировщик задач crontab
#удалять файлы и каталоги каждый час
* 0-23 * * * rm –R /samba/guest/*
#Удалить только файлы старше 1 дня, запуск команды каждые 10 минут
0-59/10 * * * * find /samba/guest/* -type f -mtime +1 -exec rm –f <> \;
#удалить файлы старше 50 минут, запуск команды каждые 10 минут
0-59/10 * * * * find /samba/guest/* -type f -mmin +50 -exec rm -f <> \;
Логи службы crontab находятся в файле /var/log/cron
Ограничение доступа к SAMBA по ip адресам
Если вам нужно ограничить доступ ко всем ресурсам SAMBA, добавьте ваши списки доступа в разделе global, а если необходимо ограничить только на определенный ресурс, в разделе этого ресурса.
[global]
hosts allow = 192.168.1.100, 192.168.1.101
hosts deny = ALL
[guest]
hosts allow = 192.168.0.0/255.255.0.0
hosts deny = 10. except 10.1.1.1
Аутентификация и авторизация пользователей
Ограничение доступа по ip адресам не всегда удобно или возможно, тогда можно использовать логины и пароли.
Сначала необходимо создать локального пользователя в системе
Если пользователь будет работать только с SAMBA ресурсами, задавать ему пароль для системы нет необходимости. Пароль для системы и для SAMBA хранятся в разных файлах и могут отличаться.
Затем необходимо добавить системного пользователя в пользователи самбы и задать ему пароль
По умолчанию для хранения паролей используется файл формата tdb, которые расположен в каталоге /var/lib/samba/private/
Изменить каталог расположения файла можно глобальным параметром passdb backend
[global]
passdb backend=tdbsam:/etc/samba/smbpassdb.tdb
tdb файлы были созданы для замены «устаревших» текстовых, если вы хотите использовать текстовые файлы, для этого используйте параметр passdb backend=smbpasswd в разделе global
passdb backend=smbpasswd:/etc/samba/smbpasswd
Затем укажите списки пользователей и групп для доступа к ресурсам
[guest]
path = /samba/guest
writable = no
read list = user1, @group2
write list = user2, user3
Интеграция с Active Directory
Также есть возможность получать информацию о пользователей из LDAP, но мне этот вариант не интересен и я сразу перехожу к AD. Подробная инструкция от Microsoft находится тут.
Для AD очень важна синхронизация времени, по этому стоит начать с этого.
Установка соответствующей службы
Добавляем в конфиг файл /etc/ntp.conf сервера выполняющих роль домен контроллеров
server 192.168.1.10
server 192.168.1.20
server someserver.contoso.com
Добавляем службу ntp в автоматический запуск
Проверяем синхронизацию времени
winbind
Для получения информации о пользователях из AD необходимо установить пакет samba-winbind
Добавляем службу в автоматический запуск
Добавление хоста в AD
Напомню что в начале даной инструкции задали имя хоста ls01.fqdn.com. Будем считать что полное имя домена fqdn.com, а короткое пусть будет fqdn_com
Для внесения всех необходимых параметров в конфигурационные файлы можно воспользоваться утилитой authconfig-tui, установите флажок Use Winbind, затем перейдите на следующее окно
Выберите модель безопасности ADS и укажите имена вашего домена. В поле домен контролер укажите “*”, это необходимо для автоматического поиска доступного домен контроллера. Затем нажмите ОК и закройте утилиту.
Для добавления хоста в AD используйте команду net ads join –U %username%, пользователь должен обладать правами на создание учетной записи ПК в домене
Если машина не добавляется в домен, добавьте FQDN имя хоста в файл /etc/hosts.
Я несколько раз все проверял, и в файл hosts я вносил изменения когда на этапе настройки сети задавал не полное имя хоста.
Для того чтобы вывести хост из домена используйте команду net ads leave –U %username%
Что делает утилита authconfig-tui?
Утилита добавляет параметры для подключения к AD в следующие файлы, параметров не много и при желании можно забить все руками.
passwd: files sss winbind
shadow: files sss winbind
group: files sss winbind
[global]
workgroup = FQDN_COM
password server = *
realm = FQDN.COM
security = ads
idmap config *: range = 16777216-33554431
template shell = /sbin/nologin
kerberos method = secrets only
winbind use default domain = false
winbind pffline logon = false
Вы могли заметить что данная утилита вносит заметно меньше параметров чем написано в инструкции от Microsoft или других инструкциях, но если так работать – то почему бы и нет?
Из инструкции Microsoft я добавляю следующие параметры в конфиг
[global]
domain master = no
local master = no
preferred master = no
os level = 0
domain logons = no
[domain users read only]
path = /samba/guest
read list = «@fqdn_com\domain users»
force create mode = 777
directory mask = 777
[domain users writable]
path = /samba/guest
read list = «@fqdn_com\domain users»
write list = «@fqdn_com\domain users»
force create mode = 777
directory mask = 777
Перезапускаем службу samba
На скриншоте видно пользователя домена который находится в одной из общих папок
Список полезных ссылок:
P.S.
Вернемся к SELINUX, чтобы SAMBA сервер мог предоставить доступ к любым каталогам необходимо выполнить следующие команды
К сожалению я так и не смог настроить работу winbind при включенном SELINUX, если подскажете как, я буду благодарен.
Источник