25
August
2022
16:00

CIFS and Samba: Connection to the General Windows folders

25 August 2022 16:00

For work, it is necessary to connect from Linux to the common Windows folder to pick up or transfer files. Organizations in 99% use computers running Windows, so you have to connect from Linux to Windows.

Samba installation of a client in Linux

sudo apt-get update
sudo apt-get install samba-client
sudo apt-get install cifs-utils

For the convenience of viewing the network environment in GUI, the file manager nautilus with the addition nautilus-lure is convenient

sudo apt-get install nautilus nautilus-share

View common network resources using a command line

Calling the Samba client for viewing server resources from the command line:

1) View common folders provided for general access on the network for local server users

smbclient -L //192.168.100.10 -U Username%Password

or

smbclient -L //servername -U Username%Password

Where: 192.168.100.10 - IP server address, servername - server name, USERNAME - local server user, password - user's password

2) viewing common folders provided for general access to the domain users

smbclient -L //192.168.100.10 -U Domain/Username%Password

or

smbclient -L //192.168.100.10 -U Username%Password -W Domain

or by name

smbclient -L //servername -U Username%Password -W Domain

Where Domain is the name of the Active Directory domain.

Or (so as not to report the password in the command parameters every time) Create a file ~/.SmbCredentials
With the entrance data:

username=имя_пользователя
password=пароль
domain=имя_standalone_сервера_или_домена

Then, joining the network catalog:

smbclient //server/share --authentication-file=/home/vladimir/.smbcredentials 

Connecting to a common Samba folder in interactive mode

The same thing, but without a key -l, but with the parameter - the name of the general folder, in this case "share"

smbclient //192.168.100.10/share -U Domain/Username%Password

or

smbclient //servername/share -U Domain/Username%Password

or

smbclient //servername/share -U Username%Password -W Domain

After a successful entrance, an invitation will appear

smb: \>

You can enter commands, for example, HELP or DIR. The SMBClient interface using commands resembles a FTP client.

Connection to general folders using the Nautilus file manager

After the launch of Nautilus, select "+ other places" on the left side of the window ** - viewing the local network will open, where you can view computers on the network that have common folders.

Solving the problem with the connection: Getting rid of the error -13 Access Denied, or nt_status_access_denied

Error:CIFS: VFS: cifs_mount failed w/return code = -13"

This error can only be solved by setting up rights on the server. To open the overall viewing folder, you need three conditions:
1) The user is indicated among the users of the server Il domain (or access type Guest is allowed)
2) provided (not limited) access to the file system.
3) Dan access to a particular network folder - for example, the user is included in the user group, to which it is given access to the common folder.

The last, third condition is the most strict. It is necessary that the server administrator grant the right to the user (include it in a group of users of a common folder).

The most interesting thing is that the administrator’s rights do not guarantee it, he will be full rights to access to a common folder, because It is necessary that the user "Administrator" be included in the group, which is granted the rights to the danu network folder. In this regard, the administrator does not differ from the OTER/NOBODY group: it will receive Mount Error (13): Permission Denied because it is not included in the group of users of the network folder.

Using the Mount command

Instead of smbclient можно использовать команду mount.

First you need to create mount points and give the right to access the folder, for example:

sudo mkdir /mnt/cifs
sudo chmod 0777 /mnt/cifs

Examples of using the Mount team with network folders:

sudo mount -t cifs //192.168.20.222/share /mnt/cifs -o user=Vlad,pass=Str0ngPa$$word
ls  /mnt/cifs
sudo umount //192.168.20.222/share
ls  /mnt/cifs

Or the same thing with the .SmbCredientials file:

sudo mount -t cifs //192.168.20.222/share /mnt/cifs -o credentials=/home/vladimir/.smbcredentials

If the name of the network folder contains gaps ("Share with Spaces in Name"), you need to enter as follows:

sudo mount -t cifs //192.168.20.222/share\ with\ spaces\ in\ name /mnt/cifs -o credentials=/home/vladimir/.smbcredentials

Note: So that after executing the mount commanded folder, it would work not only for reading, but also to write to the remote oven, you need to compare the remote user with the Linux local user, using the parameters UID = 1000, Gid-1000 . Where 1000 is to replace Linux with a UID and GID user (displayed by the command id).
Or add to the parameters -o noperm, iOCHARSET = UTF8 .
In the key keys, you can set the Samba version, which we use to connect. For example,
for SMB2: Vers = 2.0 or for smb3 Vers = 3.0 .

Examples:

sudo mount -t cifs //192.168.20.222/share\ with\ spaces\ in\ name /mnt/cifs -o user=username,pass=password,uid=1000,gid=1000

sudo mount -t cifs //192.168.20.222/share\ with\ spaces\ in\ name /mnt/cifs -o credentials=/home/vladimir/.smbcredentials,vers=2.0,noperm 

If the specified version of Samba (for example, SMB3) is not supported by the server, an error will be displayed "mount error(95): Operation not supported.".

Adding the Nofail parameter is useful when it is not known whether the remote computer (server) is turned on or not.

Mounting a network folder during download (file /etc /fstab)

Line syntax in /etc /fstab:

//[URL]/[sharename] /mnt/[mountpoint] cifs vers=3.0,credentials=/home/username/.sharelogin,iocharset=utf8,file_mode=0777,dir_mode=0777,uid=[username],gid=[username],nofail 0 0

Where:
//[URL]/[sharename] - имя сервера и сетевой папки
/mnt/[mountpoint] - точка монтирования на локальном компьютере
vers=3.0 - принудительно установить версию протокола SMB3 (либо vers=2.0 - если клиент и сервер поддерживают лишь SMB2)
credentials=/home/username/.sharelogin - указание файла с именем пользователя, паролем и доменом для входа
iocharset=utf8 - прямое указание набора символов utf8 (не обязательно, если без него работает)
file_mode=0777,dir_mode=0777 - права доступа при выполнении mount
uid=[username],gid=[username] - данные uid и gid из результата вывода команды cat /etc/passwd | grep username
nofail - загрузка ОС будет продолжена даже в случае недоступности сервера URL

Other parameters:
defaults - включает опции rw, suid, dev, exec, auto, nouser, and async. Обычно идёт первой, т.к. можно переопределить отдельные опции в строке позднее, например: defaults, noexec, ro - нет исполнения, только чтение.
rw - очевидно, чтение-запись со стороны клиента (является противоположностью ro - только чтение (защита от записи).
suid - запрещает использование бит полномочий SUID (Set-User-IDentifier - установка идентификатора владельца) или SGID (Set-Group-IDentifier). Грубо говоря, запрещает передачу части прав при помощи битов SUID и SGID - права должны быть заданы явно.
auto - используется в /etc/fstab - разрешает автоматическое монтирование сетевых ресурсов при выполнении команды mount -a
noauto - запрет для fstab монтировать папку автоматически при выполнении команды mount -a.
nouser - прямой запрет на "ручное" монтирование всеми пользователями, кроме root (не влияет на монтирование во время загрузки ОС)
guest - для доступа к "гостевым" общим папкам, которые доступны по сети без указания имени пользователя и пароля.
async - запись данных в сетевую папку производится по мере возможности - значение по умолчанию. Повышает производительность.
sync - немедленная запись на удаленный компьютер (без использования буферов), не рекомендуется.
noperm - отключает встроенную в клиент проверку прав. Используют noperm в том случае, если права вроде бы есть, но создать файл на запись, например, программно, не получается, из-за несовместимости в реализации CIFS на клиенте и сервере.
noexec - прямой запрет запуска исполнимых файлов из сетевой папки
noatime - не обновлять время создания файла (повышает производительность, но понижает информативность)
nounix - отключение расширений Linux: не использовать символические ссылки. Используется, чтобы отключить символьные ссылки для обеспечения совместимости с Windows.
mfsymlinks - ключ для символьных ссылок в стиле Minshall+French. Этот стиль ссылок поддерживается Windows и Mac.

Examples of the line in FSTAB (where the entry data are indicated in the /etc/.SmbCredientials file):

//192.168.20.222/share_name rw,auto,nofail,credentials=/etc/.smbcredentials 0 0

If in/etc/hosts or the local DNS server the names of the machines are spelled out, instead of IP addresses, you can connect a general folder named: // Server/Share.

FSTAB -based installation team:

sudo mount -a

All discs based on /etc /fstab will be changed with the exception of the "Noauto" parameter.

Brief Samba settings in Windows (protocols SMB1, SMB2, SMB3)

Samba Protocol has three versions 1, 2 and 3.
The SMB1 protocol is included if the organization has cars for Windows XP. In other cases, they try to turn off SMB1 as unsafe.

On and off in Windows 7 and Windows Server 2008R2 is made using a registry, parameters
HKEY_LOCAL_MACHINE \ System \ CurrentControlset \ Services \ Lanmanserver \ Parameters
Dword type parameters
SMB1 = 0
SMB2 = 1

In Windows 8, Windows 10, 11, Windows Server 2012, 2016 and above the PowerShell command is used

GET-SMBSERVERCONFIGURATION | Select Enablesmb1Protocol, Enablesmb2Protocol

SET -SMBSERVERCONFIGURATION -ENABLESMB2PROTOCOL $ TRUE

These commanders do not work in the early versions of Windows 7 and Windows Server 2008R2.
Also, SMB3 does not work in Win7 - for more details see.Here is WinitPro.ru.


Links:



Related publications