- Mounting samba shares from a unix client
- Namespaces
- Page actions
- Contents
- Mounting samba shares from a unix client
- General description
- Common mount.cifs options
- NetBios name resolution with WINS
- Step by Step list to get it working
- Mounting shares at logon time
- Как в Linux монтировать шару CIFS
- Подготовка
- Установка пакетов
- Сетевые порты
- Синтаксис
- Ручное монтирование
- Автоматическое монтирование CIFS через fstab
- Примеры использования опций
- Версии SMB
- Монтирование от гостевой учетной записи
- Права на примонтированные каталоги
- How to Mount Samba Share in Ubuntu Linux
- Install cifs-utils package in Ubuntu
- Mount Samba Share using the Mount Command
- Add Samba Share to /etc/fstab
- Authenticate Samba Share using Credential File
- Монтирование SMB/Samba
- Обнаружение SMB-шар
- Монтирование SMB
- Аутентификация на SMB-шаре
- Монтирование SMB-ресурсов через fstab
Mounting samba shares from a unix client
Namespaces
Page actions
Contents
Mounting samba shares from a unix client
General description
Using a share from a samba server within a unix filesystem depends on a lot of single components. You need at least the smbfs (which is no longer maintained) or the modern cifs kernel modules. Although older documentation says to use the smbfs, it has many restrictions and the cifs should be favoured. That said, I’ll describe only the cifs module in this document.
Since the cifs filesystem is included in the standard Linux kernel, it is simple to build it either as module or built in. If you build the cifs module (e.g. to get a newer version with bugfixes) and do not install it in the default location, then you may need to load it prior to mount a share or let modprobe load it via modprobe.conf in order to get the newer cifs module rather than the one shipped with your distribution.
The basic mount command is mount -t cifs // / . Each component needs its own attention.
The mount utility calls a mount helper, usually mount.cifs which calls into the kernel. The mount helper mount.cifs is the user space helper and needed to parse tcp/ip names and retrieve userid and password, and also does simple formatting of the mount options.
Server’s listen for incoming client connections via TCP/IP and thus have ip addresses, and usually tcp host names configured for them, but users often refer to the server by its «netbios name» (RFC1001 name). To mount using the cifs client, a tcp name (rather than netbios name) must be specified for the server. To resolve the to a ip address, you need either a DNS server which knows the ip address or your client needs the nss module wins. It is a shared library which must be in the path of your ldd. Usually under /usr/lib. You also have to add the wins option to hosts in your /etc/nsswitch.conf. The smbclient utility can also be used to identify the tcp name or ip address of a server (identified by its netbios name).
mountpoint must be a directory elsewhere in the filesystem which must exist.
Common mount.cifs options
Now an explaination of the options for mount -t cifs as described in man mount.cifs mount.cifs takes a lot of options, some of them are really confusing. I’ll try to mention the most important here.
- user= or username= : Thats the user which is used to authenticate against the server. If this is not given, then the environment variable USER is used. This option can also take the form «user%password» or «workgroup/user» or «workgroup/user%password» to allow the password and workgroup to be specified as part of the username.
- pass=
: specifies the CIFS password. If this option is not given then the environment variable PASSWD is used. If the password is not specified directly or indirectly via an argument to mount mount.cifs will prompt for a password, unless the guest option is specified.
- uid= : sets the uid that will own all files on the mounted filesystem. It may be specified as either a username or a numeric uid. This parameter is ignored when the target server supports the CIFS Unix extensions (which samba does per default unless you disable it).
- gid= : sets the gid that will own all files on the mounted filesystem. It may be specified as either a groupname or a numeric gid. This parameter is ignored when the target server supports the CIFS Unix extensions.
- domain= : sets the domain (workgroup) of the user
- ip= : sets the destination host or IP address.
- guest: mount the share as guest and don’t prompt for a password.
There are other options but they are not that important to be usefull beside performance and really specific things.
NetBios name resolution with WINS
All networking programs at some point need to resolve a host name to an IP-Address. Usually this is done with a call to the function gethostbyname. This call is a library function and thus is handled in user space. Glibc systems such as Linux have the feature of using more than one lookup method to fulfill such a query. This is known as nsswitch (Name Service Switch). The config file is usually found in /etc/nsswitch.conf.
If a program wants to resolve the ip address of a host named ‘wiki’ it simply calls the function gethostbyname. The lookups done are the responsibility of the underlying glibc then. Glibc reads the /etc/nsswitch.conf and loads the library mentioned in the hosts line. Thats the key point: if there is a wins entry, glibc loads the libnss_wins.so which enables the NetBios Name Lookup. You got it then, you can resolve a Windows Name to an ip address.
So its simple: install the libnss_wins.so, add to your /etc/nsswitch.conf at line hosts the wins entry and the windows name resolution works. Your network setup should be ok for this, but thats not a matter of samba.
Step by Step list to get it working
Lets assume you have one of those ARM powered NAS boxes such as Buffalo et al make under your TV set and you want to access it from a desktop Linux box somewhere in your house.
You will need the IP address of said box! Often you can find this out via the web interface of your router.
As root edit /etc/fstab using your favourite editor
e.g. sudo gedit /etc/fstab
At the end of the file add a line that looks like this:-
If you never set any users up on the NAS then it would look like this
Here is what one of my entries looks like
Now when I browse over to /mnt/oneterra I see all my files on my 1TB NAS! If I had left out the uid=myloginname I would only have read-only access, the _netdev is to tell Linux to wait for the network to be up before attempting the mount
For more try this link [1]
TODO: make a step by step list to solve most of the problems
Here’s the verbatim commands I used (SuSE 10.0 to Buffalo Link Station). Notice I knew the IP address, in my case the SMB name didn’t work and I didn’t bother making the Network Name «NetBios Name» Work as suggested above.
Mounting shares at logon time
If you want to automatically mount shares at user logon time the only way I found is doing it with the pam_mount module. It is the only way to do an authenticated mount without requiring the user to store the password in a file or entering it on a terminal.
Источник
Как в 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 .
Источник
How to Mount Samba Share in Ubuntu Linux
In this tutorial we are going to learn how to mount samba share on Ubuntu.
For this tutorial I am using Ubuntu Server 16.04, But you can use the following guide to mount Samba CIFS Share in any version of Ubuntu Linux including Ubuntu Desktop.
Install cifs-utils package in Ubuntu
In order to mount Samba share on Ubuntu we need to install the cifs-utils package.
The cifs-utils package provides the tools and utilities that need to mount samba share on Ubuntu Linux.
Mount Samba Share using the Mount Command
After installing cifs-utils package, we can use mount command to mount samba share instantly.
Once you execute the Command you will prompt for the Samba password of the samba user.
- The Server name can be the domain name or the IP Address of the Samba Server.
- It is also possible to provide the password with the mount command.
As per the above example, I used the mount command to mount samba share called documents from the Server 192.168.1.100. The mount point is /mnt and samba user is smbuser.
This time we also provided the password for the smbuser as a command option.
Add Samba Share to /etc/fstab
To mount samba share automatically when system reboot, We need to add an entry to the /etc/fstab file.
When system reboot, Ubuntu will mount the samba share specified in the /etc/fstab file.
To check the fstab file without reboot, use the mount -a command.
The mount -a command will Mount all filesystems mentioned in the fstab file.
Authenticate Samba Share using Credential File
We can use a credentials file that contains a username and password to authenticate the samba User.
First, we need to create the credentials file.
Next we need to add the username and password to the credentials file as follows.
Then we can use the credentials file to mount Samba Share on Ubuntu Server.
Mount using the mount Command
The fstab entry should be as follows.
So that is how we can mount samba share on Ubuntu Linux using the CIFS Protocol.
Источник
Монтирование 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
Источник