- Блог А
- среда, 9 марта 2011 г.
- Монтирование SMB/CIFS с авторизацией
- 17 комментариев:
- Монтирование SMB/Samba
- Обнаружение SMB-шар
- Монтирование SMB
- Аутентификация на SMB-шаре
- Монтирование SMB-ресурсов через fstab
- How to Mount SMB Share on Linux
- Install cifs-utils on Linux
- Mounting a SMB Share using CIFS
- Mount SMB share using smbmount
- Connect SMB Share using smbclient
- How to list SMB Share
- Fstab entry to mount smb
- Conclusion
- Tim Lehr
- Auto-mount Samba / CIFS shares via fstab on Linux
- 1. Install dependencies
- 2. Create mountpoints
- 3. Create a credentials file (optional)
- 4. Edit /etc/fstab
- 5. Manually mount the share for testing
Блог А
среда, 9 марта 2011 г.
Монтирование SMB/CIFS с авторизацией
- sudo mkdir /mnt/share
- sudo chown myuser /mnt/share
2. Открываем /etc/fstab
- sudo nano -w /etc/fstab
Вписываем в файл строку монтирования общего каталога
//192.168.1.1/share /mnt/share smbfs auto,user,iocharset=utf8,uid=1000,umask=000,username=AdMyUser,password=AdMyPass 0 0
//192.168.1.1/share — адрес по которому располагается общая папка
/mnt/share — созданная нами директория в которую осуществляется монтирование
smbfs — тип файловой системы
Далее идут параметры монтирования
user — разрешаем монтировать файловую систему обычному пользователю;
iocharset=utf8 — указываем кодировку (из возможных вариантов: cp1251, koi8-r);
uid=1000 — устанавливаем владельца для всех файлов, у root uid=0, а первый не рут пользователь в системе, как правило имеет uid=1000;
umask=000 — устанавливаем биты полномочий. Биты полномочий umask отличаются от chmod, для umask восьмеричное число 0 (или десятичное 000) будет равно режиму доступа rwx;
username — имя пользователя которому даны привилегии на папку
password — пароль для пользователя.
3. Сохраняем файл и выполняем
17 комментариев:
Во! Спасибо, дорогой Антон!
А если командой отдельной, то как? sudo mount.cifs . ?
sudo mount -t cifs //192.168.1.1/share /mnt/share -o auto,user,iocharset=utf8,uid=1000,umask=000
Источник
Монтирование SMB/Samba
Чтобы обеспечить наилучшую совместимость для обмена файлами между различными ОС, Samba является распространенным решением. В Linux вы можете настроить сервер Samba для предоставления доступа клиентам, использующим протоколы Server Message Block (SMB) или Common Internet File System (CIFS) для доступа к этим общим ресурсам. Вы также можете настроить Linux в качестве клиента для серверов, предлагающих общие ресурсы SMB или CIFS, что позволяет серверам получать прямой доступ к общим ресурсам Windows. В этой статье вы узнаете, как смонтировать удаленную файловую систему SMB. Эта процедура может быть применена для монтирования SMB-совместимых общих ресурсов, которые предлагаются с любой платформы, поэтому она работает на общих ресурсах Windows и Linux.
Обнаружение SMB-шар
Перед тем как смонтировать общий ресурс SMB, убедитесь, что на клиентском компьютере установлены пакеты RPM cifs-utils и samba-client. Также вам необходимо добавить службу samba-client в конфигурацию брандмауэра на клиенте с помощью firewall-cmd —add-service samba-client —permanent; firewall-cmd —reload. После установки вы можете использовать команду smbclient -L для обнаружения доступных общих ресурсов SMB.
Команда smbclient запрашивает пароль текущего пользователя. Это связано с тем, что smbclient — это очень общая утилита, которая позволяет составлять список общих ресурсов, а также входить в общие ресурсы Samba на удаленных серверах и извлекать файлы с удаленного сервера. Однако для составления списка шар учетные данные не требуются. Итак, когда команда просит
пароль, вы можете просто нажать Enter. В качестве альтернативы вы можете использовать опцию -Uusername с smbclient для аутентификации с использованием действительной учетной записи пользователя Samba.
Вывод команды smbclient -L
]# smbclient -L 192.168.122.201
Enter root’s password:
Anonymous login successful
Domain=[MYGROUP] OS=[Unix] Server=[Samba 4.1.1]
Sharename Type Comment
——— —- ——-
data Disk Demo data directory
homedirs Disk LDAP user home directories
IPC$ IPC IPC Service (Samba Server Version
4.1.1)
Anonymous login successful
Domain=[MYGROUP] OS=[Unix] Server=[Samba 4.1.1]
Server Comment
——— ——-
IPA Samba Server Version 4.1.1
Workgroup Master
——— ——-
MYGROUP IPA
В спойлере вы можете увидеть, как утилита smbclient используется для обнаружения доступных общих ресурсов по IP-адресу 192.168.122.201. (Чтобы обойти возможные проблемы с разрешением имен, вместо имени используется IP-адрес хоста.) Затем команда запрашивает пароль текущего пользователя. Поскольку опция -L запрашивает только список доступных общих ресурсов и ничего больше, вы можете просто нажать Enter, чтобы проигнорировать этот вопрос. Далее отображается текущий домен или рабочая группа сервера Samba, а также доступные общие ресурсы.
В качестве альтернативы вы можете использовать команду net share -l. Эта команда перечисляет только общие ресурсы, доступные на сервере Samba, и не отображает дополнительную конфигурацию, которая отображается при использовании smbclient -L. Обратите внимание, что команда net share -l также выводит список общих принтеров, тогда как smblcient -L просто отображает общие каталоги. Команда net доступна в Linux для предоставления интерфейса командной строки, который более знаком администраторам Windows, которые хотят настроить общий доступ к файлам с сервера Linux.
Вывод результата команды net share -l
]# net share -l
Enter root’s password:
Anonymous login successful
Enumerating shared resources (exports) on remote server:
Share name Type Description
———- —- ————
sambashare Disk Sambashare
IPC$ IPC IPC Service (Samba Server Version 4.1.12)
textprinter Print textprinter
DummyPrinter Print DummyPrinter
Монтирование SMB
Чтобы смонтировать общий ресурс SMB, вы можете использовать команду mount. Вы можете использовать опцию -t cifs, чтобы указать, что монтируется на общий ресурс SMB, но без этой опции он также будет работать, потому что команда mount достаточно умна, чтобы самостоятельно определить, что это общий ресурс SMB, к которому вы хотите подключиться. Если на общем ресурсе разрешен гостевой доступ, вы можете указать опцию -o guest для аутентификации в качестве гостевого пользователя без пароля. Или же используйте параметр -o user = guest для той же цели.
Полная команда монтирования выглядит следующим образом:
mount -t cifs -o user=guest //192.168.122.200/data /mnt
Эта команда монтирует общий ресурс /data, который доступен на 192.168.122.200 в локальном каталоге /mnt. Обратите внимание, что вы сможете получить доступ к файлам в общем ресурсе, но не сможете записывать какие-либо файлы в общем ресурсе, потому что вы аутентифицированы как гостевой пользователь с ограниченными правами доступа к общему ресурсу.
Аутентификация на SMB-шаре
Выше вы прочитали, как подключить общий ресурс с учетными данными гостя. Если вы хотите что-то сделать с общим ресурсом, вы должны аутентифицироваться как действительный пользователь Samba. Это конкретная учетная запись пользователя, которая имеет учетные данные, необходимые для подключения к общему ресурсу Samba. (Обычный пользователь Linux не может этого сделать.) Для этого должен быть создан пользователь Samba.
Чтобы указать имя пользователя Samba, которое вы хотите использовать, вы можете добавить опцию -o username=someone:
mount -o username=sambauser1 //server/share /somewhere
Когда вы делаете это, команда mount запрашивает пароль. Ниже пример, как находить и монтировать общие ресурсы Samba.
1. Зайдите на сервер под рутом.
2. Введите yum install -y cifs-utils samba-client, чтобы установить необходимые пакеты RPM.
3. Введите smbclient -L 192.168.122.200, чтобы получить список доступных общих ресурсов на сервере.
4. Введите mount -t cifs -o guest //192.168.122.200/data /mnt, чтобы смонтировать общий ресурс /data в качестве гостя в каталоге /mnt.
5. Введите mount, чтобы убедиться, что монтирование прошло успешно.
Монтирование SMB-ресурсов через fstab
В качестве альтернативы указанию учетных данных в файле /etc/fstab напрямую, вы можете использовать файл учетных данных. При использовании файла учетных данных сам файл учетных данных содержит имя пользователя, пароль и (необязательно) домен, к которому вы хотите подключиться. При использовании файла учетных данных его необходимо обязательно защитить. Лучший путь
чтобы защитить его, поместите его в домашний каталог пользователя root, установите для владельцев значение root:root и установите права 600.
Содержимое файла creds может выглядеть так
Расположение файла учетных данных описано в man mount.cifs.
Чтобы использовать файл учетных данных при монтировании из командной строки, вы можете включить параметр -o credentials=filename, как показано ниже:
Чтобы сделать то же самое из файла /etc/fstab, в файл /etc/fstab необходимо включить следующую строку:
Новость отредактировал: yatakoi — 28-12-2020, 16:13
Причина: В статью добавлено монтирование SMB через fstab
Источник
How to Mount SMB Share on Linux
SMB is a protocol used by Windows-based computers for sharing access to resources on a network. To mount SMB share, Linux kernel now supports SMB3 by default (SMB3.1.1/SMB3.02/SMB3/SMB2.1 dialects are requested by default).
CIFS is a particular implementation of the Server Message Block (SMB) protocol. CIFS is a dialect of SMB.
The cifs-utils provide user-space tools to mount SMB/CIFS share on Linux. In this tutorial, I will show you how to mount smb shares on Linux.
Install cifs-utils on Linux
To mount SMB/CIFS share we required cifs utils package installed on the Linux.
Run the following command to install cifs-utils on Ubuntu and Debian:
To install cifs-utils on RHEL, Centos, or Fedora, type following command:
For Fedora28 and above use dnf package to install cifs-utils:
Mounting a SMB Share using CIFS
In this section, the tutorial will show you the way to mount a SMB share using CIFS on Linux systems.
A SMB share can be mounted on your mount point using ‘cifs’ option of mount command. In the following example, we use the SMB 1 protocol to mount the share by using the ‘-o vers=1.0’ option:
By default, the Linux kernel uses the latest SMB protocol version supported by the operating system. In the following command, we will mount a SMB share without passing the ‘vers=’ option:
If the user is in a windows domain, specify the domain as the following command:
By default, linux mount windows share with the full permission (rwx or 777). If you want to change the permission on your own, please use the dir_mode and file_mode options to set permission for directory and file.
You also can change the default ownership of user and group by specify the uid (user id) and gid (group id) options.
Mount SMB share using smbmount
Smbmount command is used to mount a Linux SMB filesystem. Although it was deprecated and no longer maintained, you still can use smbmount to mount a SMB share by running the following command:
Here NAS samba share is mounted with lfs (large file system) option enabled. This will avoid errors while copying a large file from NAS storage.
Connect SMB Share using smbclient
This package is not included by default on most Linux distributions, so you will need to install it with your local package manager.
On Debian and Ubuntu servers install smbclient with the following command:
- sudo apt-get update
- sudo apt-get install smbclient
The smbclient is a client program that is part of the Samba suite which acts like a FTP program. You can connect to share, use get and put commands to transfer files.
How to list SMB Share
The smbclient command can be also used to list the shared smb resource on remote Samba Server.
Use the following smbclient -L command to displays the shared smb resources on remote server ‘192.168.1.100’:
Fstab entry to mount smb
The fstab entries make sure that your mount is persistent over reboot. The following example shows fstab entries for smb share:
Here local user (uid=500) will become the owner of the mounted files. In a similar way, you can specify credentials such as uid=uid number or name of the account/user or group.
The /etc/fstab is readable by everyone so it obviously wouldn’t be a good idea to have your Windows password in it. The way to get around this is, by using what is known as a credentials file.
Below echo command can be used to create the credentials file:
Modify the permissions on the file so only you have permission to read and write to it.
Conclusion
In this tutorial, we learned how to mount smb share on Linux. Samba supports using SMB1.0, SMB2.0 and SMB3 and defines server min protocol option in smb.conf file.
On Linux clients, you can install cifs-utils that provides means for mounting SMB/CIFS shares.
If you have any questions or feedback, feel free to leave a comment.
Источник
Tim Lehr
Technical Director | Pipeline Developer
Auto-mount Samba / CIFS shares via fstab on Linux
I’ve been a happy Linux user for quite a while now, but even I cannot deny that it’s sometimes quite hard to get things running smoothly – especially in a Windows dominated environment with little control. One of the things that breaks once in a while on my workstation is the automatic network share mounting I set up via /etc/fstab. This is usually caused by some server-side update that doesn’t affect the setups of Windows and Mac users, but can break your fstab mounting commands in a heartbeat.
Unfortunately, when things break, the feedback you get from running mount -a is often rather generic and of little help. A typical error:
Not too helpful, is it? Debugging issues like this one can be quite tedious and time consuming, so I decided to write a little guide to mounting Windows (Samba) network shares on Linux (Fedora 26 in my case). There are a lot of guides out there already, but I found some things especially important and wanted to point those out. Let’s get started.
1. Install dependencies
Install the necessary “cifs-utils” with the package manager of your choice e.g. DNF on Fedora.
2. Create mountpoints
Create a directory (mountpoint) in /media for every network share you want to mount. If /media does not exist yet, create it first. This is the location where you commonly mount removable volumes in Linux. After the mount is successful, you access all files on your network share from that directory, so be sure to give it a good name. e.g. /media/mordor
3. Create a credentials file (optional)
Usually network shares have access protection, so you’ll want to store your user credentials in a local credentials file. If you don’t want this, you’ll have to specify the credentials everytime you want to mount, so I highly recommend it, as long as it’s your machine you are mounting on. The credential file should be in any location in your user directory, e.g. /home/tim/.smb, and should look similiar to this:
4. Edit /etc/fstab
Now you should be all set and ready to edit your /etc/fstab file to do some mount magic. Just open the file with a text editor of your choice and add the following lines to the bottom of the file.
Important: Do not change or delete any other lines in the file! This can do serious harm to your system configuration and you might end up with a broken OS. You have been warned.
Notice the small difference? If things do not work, it’s usually because the “vers” argument is not set or incorrect. It specifies the Samba version to be used and depending on your server setup this might range from “vers=1.0″ to “vers=3.0″. In my experience you best start of trying to mount the share without it and try-again with different settings if this doesn’t work out.
For Windows server 2008 shares I can usually get away without it. In more recent versions like Windows Server 2016 it likely needs to be “vers=2.1″ or “vers=3.0″. However, my experience so far is limited to Fedora and a single network, so you might have to tweak the value some more.
5. Manually mount the share for testing
Although entries in /etc/fstab are automatically mounted when the system boots, it’s pretty annoying to debug your mount command this way. Here are two commands handy to manually mount and unmount all entries in fstab.
If you run the first command and do not get any errors, the mounting seems to have worked out fine. Don’t forget to check your mountpoint to make sure you have read / write access!
If you have any issues with your setup, feel free to leave a comment and I’ll try my best to help you out, although I’m far from being an expert on this topic. Good luck!
Источник