Linux samba mount fstab

Монтирование 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.

Читайте также:  Opening windows programs on mac

Чтобы указать имя пользователя 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

Источник

Configure a system to automount a Samba share with /etc/fstab

The /etc/fstab file contains static information about the filesystems. The file fstab contains descriptive information about the various file systems. fstab is only read by programs, and not written; it is the duty of the system administrator to properly create and maintain this file.

To mount a Samba share to be mounted when a Linux system comes up after reboot edit the /etc/fstab file and put entry as follows for your Windows/Samba share:
//ntserver/share /mnt/samba smbfs username=username,password=password 0 0

For example, if you want to mount a share called //ntserver/docs then you need to write following entry in /etc/fstab file:
//ntserver/docs /mnt/samba smbfs username=docsadm,password=D1Y4x9sw 0 0
Where,

  • //ntserver/docs: Windows 2003/NT/Samba share name
  • /mnt/samba: Local mount point (you may need to create this directory first)
  • smbfs: File system type (samba file system)
  • username=docsadm,password=D1Y4x9sw: Share username and password

Open file /etc/fstab using vi text editor:
# vi /etc/fstab Append line
//ntserver/docs /mnt/samba smbfs username=docsadm,password=D1Y4x9sw 0 0, at the end your file should read as follows:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Replace sharename, username and password with your actual parameters.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Okay, but the use of the term “automount” here
is misleading. I was looking for how to configure
autofs to work with samba shares.

It disturb me that username and passwd appears clearly in the fstab file. Is there another solution ?

Try to put password/username in different file and make sure password file is only accessed by root. See url for an example:

I have to agree with Scott, “automount” in the title is misleading. I too was looking for info on configuring samba with autofs.

The following link might be useful to Scott and also has details on moving the username/password to a different file.

first create the below in root home directory:

cd
echo username=mywindowsusername > .smbpasswd
echo password=mywindowspassword >> .smbpasswd
chmod 600 .smbpasswd

Then the below line will be changed:
//ntserver/docs /mnt/samba smbfs username=docsadm,password=D1Y4x9sw 0 0

To :
//servername/sharename /mountdirectory smbfs credentials=/home/myhomedirectory/.smbpasswd 0 0

I’ve put the entry in fstab and put the credentials in another file. It works fine, thank you, but although I can write to the share as root, I can’t as a normal user. I’ve tried chmod on the mount point, but that didn’t work, any ideas?

try this:
//servername/sharename /mountdirectory smbfs credentials=/home/myhomedirectory/.smbpasswd,uid=user,gid=user 0 0

Thanks for the feedback. This actually prompted me to do a little more research on the options and as this share is just a dumping ground I decided to use

//servername/sharename /mountdirectory smbfs credentials=/home/myhomedirectory/.smbpasswd,fmask=666,dmask=777 0 0

so that it’s writeable by everyone.

Thank you for information

I’d like to ask a question and I don’t think the solution is out there….I have a samba share setup that will only allow connections from my LAN IP addresses…therefore, I don’t need user/pass security setup on it.

I have configured it as an open share writeable and readable by anyone connecting from MY LAN. This works through browsing local network in KDE/Gnome or even in Windows. This is nice for my friends who come by and want to connect to my music/movie/game share.

However, I cannot configure a Linux /etc/fstab to mount the share because it keeps asking for a username and password. There IS NO USERNAME nor PASSWORD. So, how does one enter the information so that it can be processed and mounted by fstab?

I think this would be a great ‘how-to’ for you to feature like this article…because there is NOTHING out there on how to do this.

yeah, i am also looking for a solution to the no username/password access to a windows share…

@John and curious mounter
the “guest”-option will do.

-> man mount.cifs (line 85)

hai
i want shared data from windows to linux system.. how can i share different way. plz any one mail to me.
same time i want to modified my pdf file. any pdf writer in linux plz intimated me.

hai
i want shared data from windows to linux system.. how can i share different way. plz any one mail to me.
same time i want to modified my pdf file. any pdf writer in linux plz intimated me.

yours
Manikandan KM

loopo, I got excited at the NO USERNAME/NO PASSWORD discussion raised by John and curious mounter, and I appreciate your response that “the “guest”-option will do. -> man mount.cifs (line 85)”, but as I’m a growing newbie, I’m not sure how to apply your response (though I think I understood all the thread up to the point that you responded about the guest option and the arrow point). Currently, Dolphin has no problem accessing my DLink NAS (well, at first it stumbles and doesn’t recognize it, but after I go to Network and work my way to it, it appears with my bookmark, though sometimes it doesn’t even appear under Network until I go to Firefox and use the 192.168.x.xxx call, then it “suddenly” appears when I return to Network — I guess it’s one of those mounting things).

I note that Konqueror seems unable to work with 192.168.x.xxx to configure the NAS, but Firefox always has no trouble with this.

Maybe this is a different problem (or maybe it’s related to the fstab needing to be done first), but what I MOST want to do is have programs (VLC, K9, etc.) to be able to access my DLink NAS, but they seem blind to it through their file access dialog boxes. For example, VLC plays DVD iso’s just fine if it is on a local drive and I drag-&-drop it from Dolphin, but if it is on my NAS, VLC does not recognize the file unless I first copy it with Dolphin to a local drive, then after a drag-&-drop from the local drive, it plays just fine (again, it’s a DVD iso). I’d also like to use K9 to put DVD iso’s directly on the NAS (instead of running them to a local drive from K9 and then later copying them to the NAS for storage), but K9 just doesn’t seem to acknowledge that the NAS exists through its dialog boxes (though Dolphin shows it’s there plain as day after it’s mounted).

If I do the fstab trick in this thread (well, once I understand how to apply your solution), will it solve my problem with VLC & K9, etc.? I have NO NAME & NO PASSWORD like the previous writers mentioned on my NAS so everyone in the house can use it (all the dual-boot Windows based computers on the network have no difficulty whatsoever with the NAS with VLC etc., it’s just the dual-boot Linux systems that stumble from their dialog boxes in a variety of Linux-based programs that are very important to us — we’re trying to get away from Windows completely but we haven’t learned how to do some things with Linux yet).

I am also using the “ip instead of password” idea.

If I am reading this right, user “guest” as the username and leave off the password.

password=arg
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.
and guest described…
guest
don’t prompt for a password

Beware that if you add an option like “user” to fstab then a simple user can do:
mount –verbose /xxx and he will eventually see the username/password even if you used the credentials=… approach

People who want to automount specific shares for specific users when they log in should investigate the pam_mount library. It is secure and more appropriate on an untrusted network environment.

It’s a bit more complicated to set up than this, though. There are various tutorials out there and it can vary a little between the distros.

Wow, this tutorial is simple and easy for a beginner like me, the comments are especially helpful, although I use the parameter of rw,exec, user

How to make the /etc/fstab line work in Fedora 12? smbfs isn’t available.

@adam: try “cifs” instead of “smbfs”

I have mounted a windows share before, however had a problem when the linux box was rebooted, the operating system would hang because the network had not connected in order to mount the windows share.

So my question is this, how do you have the automount happen after the network connection?

Here’s my fstab entry:

//windowsshare/dir /mnt/point cifs rw,domain=DOMAIN,credentials=/path/filename,fmask=0664,dmask=0775

Please also update or have a note that new linux systems might use CIFS file system.. then the conf would change to
//ntserver/docs /mnt/samba cifs username=docsadm,password=D1Y4x9sw 0 0

Is is possible to use an ip address for share as well – for example:
//192.168.0.106/home /mnt/samba smbfs username=username,password=password 0 0

guys, please I need help.
I am not that expert in NFS, but what happened that I am runnning calculation on a pc cluster which is connected to NFS server called “//bourbon/home10” through another computer “hoppy”(the japanese people in my lab call it name server).
what happened is this client computer”hoppy” gave an error and tried to automount old servers which were removed pretty while ago. it gives mounting error.
and when I try to go to bourbon/home10 it doesnt show any subdirctories.
any idea about what is happening here?

Источник

Читайте также:  Наиболее популярные системы windows
Оцените статью