Ubuntu смонтировать сетевую папку windows

Duplicate Article
This article covers the same material as another article. More info…

Contents

  1. Introduction
  2. Prerequisites:
  3. Enable Name Resolution
  4. Install cifs-utils
  5. Manual mounting from the command line

    1. Most basic mount command
    2. Unmounting
    3. Mount with read/write access
    4. Mount with authentication — next line
    5. Mount with authentication — same line
    6. Mount with authentication — file
  6. FSTAB

    1. FSTAB with inline authentication
    2. FSTAB with file authentication
  7. If you need even more security
  8. Troubleshooting

    1. Common mistakes
    2. Common error messages

Introduction


This document will cover how to connect to a Windows file share from the Linux command line on a single-user machine or a machine where all the users are ok with the other users having access to the mounted share. This method gives you considerably higher performance compared to the userland mounts that most GUI programs create. (just check out the benchmark at MountCifsFstabBenchmark) This method has been tested with Ubuntu 14.04 thru 20.04 and with Windows XP,7,10, and Server2019.

Prerequisites:


  • A machine running Ubuntu 14.04 or newer
  • A machine running Windows XP or newer
  • The IP address or hostname of the Windows machine
  • The name of the file share on the Windows machine
  • A Windows username and password with permission to the file share
  • root access to the Ubuntu machine. Pretty much every command on this page requires root.

Enable Name Resolution


This optional step requires Ubuntu 18.04 or newer and allows you to use the hostname of your windows machines instead of its IP address.

First, install winbind and libnss-winbind

apt install winbind libnss-winbind

then, edit nsswitch.conf and find the line that starts with «hosts» and add «wins» after «files»

nano /etc/nsswitch.conf

BEFORE: hosts: files mdns4_minimal [NOTFOUND=return] dns )

AFTER: hosts: files wins mdns4_minimal [NOTFOUND=return] dns ) restart the winbind service

systemctl restart winbind

Install cifs-utils


Ubuntu’s kernel has built-in support for mounting Windows file shares. It’s called the cifs kernel client, and it’s considerably faster than the mounts created by GUI programs such as nautilus and caja and thunar and some command line programs such as gio.

To be able to control the kernel’s cifs client, you’ll need to install cifs-utils:

apt install cifs-utils

Manual mounting from the command line


All of these commands require root permission, so let’s just start bash with root so we don’t have to type sudo on everything:

sudo bash

You’ll need to create a folder to host the mount point:

mkdir /mnt/share1

Most basic mount command


This command will only work if the windows machine as the “Turn OFF password protected sharing” option set.

Let’s start out with the most basic form of the mount command that actually works:

mount //win10/share1 /mnt/share1

When it asks for a password, don’t type one, just press enter. (replace “win10” with the hostname of your windows machine) (replace the first “share1” with the name of the file share on your windows machine) This command is actually all you need if the windows machine has the “Turn OFF password protected sharing” option set. You will have read/write permission to the share as long as you have root permissions in Linux. You will only have read-only access to the mount from GUI programs because GUI programs don’t normally run with root permission.

Unmounting


To UNmount it:

umount /mnt/share1

(notice it’s not unmount, it’s umount)

Mount with read/write access


In order to get read/write access to your mount from GUI programs or without root permissions, you’ll need to tell the kernel which Linux users are allowed to have read/write access to the mount. If you want ALL Linux users to have read/write access to the mount, you’ll want to use the noperm option, like this:

mount -o noperm //win10/share1 /mnt/share1

When it asks for a password, don’t type one, just press enter. -o means mount options are specified next noperm means “client does not do permission check”, which is going to get you read/write access to the mount replace “win10” with the hostname of your windows machine replace the first “share1” with the name of the file share on your windows machine

Mount with authentication — next line

Now let’s assume the windows machine has the “Turn ON password protected sharing” option set, so you will need to specify a windows username and password to access the share.

mount -o noperm,username=john,domain=domain1 //win10/share1 /mnt/share1

When it asks for a password, enter the windows password that goes with the windows account.

-o means mount options are specified next

noperm means “client does not do permission check”

replace “john” with the windows username. The windows machine will need to have an account matching this username, and this account needs to have permissions to the file share

replace “domain1” with the name of your active directory domain. If you don’t know what an active directory domain is, you don’t have one, so just leave this option blank or remove it.

replace “win10” with the hostname of your windows machine

replace the first “share1” with the name of the file share on your windows machine

Mount with authentication — same line

Let’s take it one step future and specify the password on the command line too so we don’t have to type it. This could be useful for scripts, but…

SECURITY WARNING: Keep in mind that anybody that has permissions to read the script file will be able to see your windows account password. The password would also be visible briefly in the output of the ps command or any command that shows a list of processes, and even non-root Linux users can see this list. Any program that logs commands would also log the password, including bash’s .history file which is enabled be default.

mount -o noperm,username=john,password=123,domain=domain1 //win10/share1 /mnt/share1

-o means mount options are specified next

noperm means “client does not do permission check”

replace “john” with the windows username. The windows machine will need to have an account matching this username, and this account needs to have permissions to the file share

replace “123” with the windows password

replace “domain1” with the name of your active directory domain. If you don’t know what an active directory domain is, you don’t have one, so just leave this option blank or remove it.

replace “win10” with the hostname of your windows machine

replace the first “share1” with the name of the file share on your windows machine

Mount with authentication — file

If you don’t like having those security risks, you can put the windows username and password in a separate file, and make that file readable only by root:

mount -o noperm,credentials=/root/creds.txt //win10/share1 /mnt/share1

-o means mount options are specified next

noperm means “client does not do permission check”

replace “/root/creds.txt” with the file that contains the windows username/password

replace “win10” with the hostname of your windows machine

replace the first “share1” with the name of the file share on your windows machine

Now we need to create our creds.txt file

nano /root/creds.txt
username=john
password=123
domain=domain1

replace “john” with the windows username. The windows machine will need to have an account matching this username, and this account needs to have permissions to the file share

replace “123” with the windows password

replace “domain1” with the name of your active directory domain. If you don’t know what an active directory domain is, you don’t have one, so just leave this option blank or remove it.

You can make it readable only by root:

chmod 600 /root/creds.txt

FSTAB


If you want to have persistent mounts, so that the mounts get mounted automatically at boot time, you can use the fstab file.

nano /etc/fstab

If the windows machine has the “Turn OFF password protected sharing” option set, and you want all Linux users to have read/write permissions to the share, add this line to the bottom of the fstab file:

//win10/share1  /mnt/share1     cifs    noperm,_netdev  0       0

replace “win10” with the hostname of your windows machine

replace the first “share1” with the name of the file share on your windows machine

cifs tells the kernel to use mount.cifs as opposed to ext3 or ntfs or some other type of file system

noperm means “client does not do permission check”. This is required for read/write permissions from non-root linux users. You can safely remove this option if you only want root to have read/write and other users will have read-only

_netdev will cause the kernel to wait on the network to become ready before attempting the mount. Without this option, the mount will probably fail during boot because the network won’t be ready yet

the 2 zeros tell the kernel we don’t want to dump or check the filesystem

Now you can mount and unmount with very simple commands:

mount /mnt/share1
umount /mnt/share1

(you’ll need to be root though, unless you want to adjust your sudoers file to allow non-root users to have this ability)

FSTAB with inline authentication


Now let’s assume the windows machine has the “Turn ON password protected sharing” option set, so you will need to specify a windows username and password to access the share. SECURITY WARNING: Keep in mind that anybody that has permissions to read the fstab file will be able to see your windows account password, and the fstab file is readable by all Linux users by default!

//win10/share1  /mnt/share1  cifs  noperm,_netdev,username=john,password=123,domain=domain1  0   0

replace “win10” with the hostname of your windows machine

replace the first “share1” with the name of the file share on your windows machine

cifs tells the kernel to use mount.cifs as opposed to ext3 or ntfs or some other type of file system

noperm means “client does not do permission check”. This is required for read/write permissions from non-root Linux users. You can safely remove this option if you only want root to have read/write and other users will have read-only

_netdev will cause the kernel to wait on the network to become ready before attempting the mount. Without this option, the mount will probably fail during boot because the network won’t be ready yet

replace “john” with the windows username. The windows machine will need to have an account matching this username, and this account needs to have permissions to the file share

replace “123” with the windows password

replace “domain1” with the name of your active directory domain. If you don’t know what an active directory domain is, you don’t have one, so just leave this option blank or remove it.

the 2 zeros tell the kernel we don’t want to dump or check the filesystem

FSTAB with file authentication


If you aren’t cool with all linux users being able to see your windows password, or you don’t want programs you run without root to be able to see your windows username and password, you can put the windows username and password in a separate file, and make that file readable only by root:

//win10/share1  /mnt/share1     cifs    noperm,_netdev, credentials=/root/creds.txt     0       0

replace “win10” with the hostname of your windows machine)

replace the first “share1” with the name of the file share on your windows machine)

cifs tells the kernel to use mount.cifs as opposed to ext3 or ntfs or some other type of file system)

noperm means “client does not do permission check”. This is required for read/write permissions from non-root Linux users. You can safely remove this option if you only want root to have read/write and other users will have read-only)

_netdev will cause the kernel to wait on the network to become ready before attempting the mount. Without this option, the mount will probably fail during boot because the network won’t be ready yet)

replace “/root/creds.txt” with the file that contains the windows username/password) (the 2 zeros tell the kernel we don’t want to dump or check the filesystem)

Now we need to create our creds.txt file:

nano /root/creds.txt
username=john
password=123
domain=domain1

replace “john” with the windows username. The windows machine will need to have an account matching this username, and this account needs to have permissions to the file share replace “123” with the windows password replace “domain1” with the name of your active directory domain. If you don’t know what an active directory domain is, you don’t have one, so just leave this option blank or remove it. You can make it readable only by root:

chmod 600 /root/creds.txt

If you need even more security


This should cover the majority of home and business use cases. In more complex business environments, you might need to setup a mount that some users have read-only access to, and other users have full read/write, and other users have no access at all. The usermode fuse cifs client (which is what gui programs like natulus and caja use) is the easy answer to this, but there is a huge performance penalty. If you need fancy permissions AND speed, check out the MountCifsFstabSecurely page.

Troubleshooting


If you are having a problem with the FSTAB method, try the manual mounting method and you will likely discover your problem.

— If you have access to another windows computer, see if it will mount the fileshare properly.

— Check the kernel log after you get a mount error to see if it logged a more useful error message:

dmesg

Ignore the white messages. Only the red messages are relevant. Search the internet for these error message(s)

Common mistakes

— Don’t use backslashes in the windows unc paths, always use forward slashes

  • Incorrect: \\win10\share1 Correct: //win10/share1

— Don’t put spaces in the credentials options.

  • Incorrect: username = john Correct: username=john

— If your windows password has special characters in it, like spaces or symbols, you might need special escape codes to make Linux read the password properly.

Common error messages

— mount: /mnt/share1: cannot mount //win10/share1 read-only.

  • You need to install cif-utils

— mount error: could not resolve address for …: Unknown error

  • You need to Enable Name Resolution (see section above)

— mount error(2): No such file or directory

  • The windows machine couldn’t be found. Can you ping it? OR the share name isn’t valid. Try this command to see if you can see the list of shares:
apt install smbclient
smbclient -L \\win10 -U john

— mount error(13): Permission denied

  • Your windows username or password isn’t being accepted by the windows machine. Check the windows account to make sure “force user to change password on next login” isn’t on, and make sure “disable account” is off.

— mount error(112): Host is down

  • You are probably using Ubuntu 16.04 or older with Windows 10 or newer. You can make your mount work by adding «vers=3.0» to the options.

— The mount command appears to hang when mounting a share on a Windows XP or older computer and smbclient throws «protocol negotiation failed: NT_STATUS_IO_TIMEOUT».

  • You can make your mount work by adding «vers=1.0» to the options.

В этой статье мы рассмотрим, как в Linux смонтировать общую сетевую папку, расположенную на хосте Windows. В Windows для доступа к общим сетевым папкам используется протокол SMB (Server Message Block), который ранее назывался CIFS (Сommon Internet File System). В Linux для доступа к сетевым папкам Windows по протоколу SMB можно использовать клиент cifs-utils или Samba.

    Содержание:

  • Смонтировать сетевую папку в Linux с помощью cifs-util
  • Автоматическое монтирование сетевой папки в Linux
  • Linux: подключиться к сетевой папке с помощью клиента samba

Совет. Для доступа к сетевым папкам по SMB/CIFS используется порт TCP/445. Для разрешения имени используются порты UDP 137, 138 и TCP 139. Если эти порты закрыты, вы сможете подключиться к сетевой папке Windows только по IP адресу.

Смонтировать сетевую папку в Linux с помощью cifs-util

Вы можете смонтировать сетевую папку, находящуюся на Windows хосте, с помощью утилит из пакета cifs-util. Для установки пакета выполните команду:

  • В Ubuntu/Debian: $ sudo apt-get install cifs-utils
  • В CentOS/Oracle/RHEL: $ sudo dnf install cifs-utils

Создайте точку монтирования:

$ sudo mkdir /mnt/share

Теперь вы можете смонтировать сетевую папку с компьютера Windows под пользователем User03с помощью команды:

$ sudo mount.cifs //192.168.31.33/backup /mnt/share -o user=User03

Укажите пароль пользователя Windows для подключения к сетевой папке.

mount.cifs подключить сетевую папку smb в linux

При подключении сетевой SMB папки можно задать дополнительные параметры:

$ sudo mount -t cifs -o username=User03,password=PasswOrd1,uid=1000,iocharset=utf8 //192.168.31.33/backup /mnt/share

  • //192.168.31.33/backup – сетевая папка Windows
  • /mnt/share – точка монтирования
  • -t cifs – указать файловую систему для монтирования
  • -o опции монтирования (эту опцию можно использовать только с правами root, поэтому в команде используется sudo)
  • username=User03,password=PasswOrd1 – имя и пароль пользователя Windows, у которого есть права доступа к сетевой папке. Можно указать имя пользователя guest, если разрешен анонимный доступ к сетевой папке
  • iocharset=utf8 – включить поддержку кодировки UTF8 для отображения имен файлов
  • uid=1000 – использовать этого пользователя Linux в качестве владельца файлов в папке

команда mount cifs в linux

По умолчанию шары Windows монтируются в Linux с полными правами (0755). Если вы хотите изменить права по-умолчанию при монтировании, добавьте в команду опции:

dir_mode=0755,file_mode=0755

Если вы хотите использовать имя компьютера при подключении сетевого каталога Windows, добавьте в файл /etc/hosts строку:

IP_АДРЕС    ИМЯ_КОМПЬЮТЕРА

Чтобы не указывать учетные данные пользователя Windows в команде монтирования сетевой папки, их можно сохранить в файле.

Например:

$ mcedit ~/.windowscredentials

Добавьте в файл:

username=User03
password=PasswOrd1

Для подключения к папке под анонимным пользователем:

username=guest
password=

Если нужно указать учетную запись пользователя из определенного домена Active Directory, добавьте в файл третью строку:

domain = vmblog.ru

Измените права на файл:

$ chmod 600 ~/.windowscredentials

Теперь при подключении сетевой папки вместо явного указания имени пользователя и пароля можно указать путь к файлу:

$ sudo mount -t cifs -o credentials=/home/sysops/.windowscredentials,uid=1000,iocharset=utf8 //192.168.31.33/backup /mnt/share

Отмонтировать сетевую SMB папку:

$ sudo umount /mnt/share

Автоматическое монтирование сетевой папки в Linux

Можно настроить автоматическое монтирование сетевой папки Windows через /etc/fstab.

$ sudo mcedit /etc/fstab

Добавьте в файл следующую строку подключения SMB каталога:

//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev 0 0
  • rw – смонтировать SBM папку на чтение и запись
  • nofail – продолжить загрузку ОС если не удается смонтировать файловую систему
  • _netdev – указывает что подключается файловая система по сети. Linux не будет монтировать такие файловые системы пока на хосте не будет инициализирована сеть.

Вы можете указать версию протокола SMB, которую нужно использовать для подключения (версия SMB 1.0 считается небезопасной и отключена по-умолчанию в современных версиях Windows). Добавьте в конец строки с настройками подключения параметр vers=3.0.

//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev,vers=3.0 0 0

Если на стороне хоста Windows используется несовместимая (старая версия) SMB, при подключении появится ошибка:

mount error(112): Host is downилиmount error(95): Operation not supported

Чтобы сразу смонтировать сетевую папку, выполните:

$ mount -a

Linux: подключиться к сетевой папке с помощью клиента samba

Установите в Linux клиент samba:

  • В Ubuntu/Debian: $ sudo apt-get install smbclient
  • В CentOS/Oracle/RHEL: # dnf install smbclient

Для вывода всех SMB ресурсов в локальной сети:

$ smbtree -N

Вывести список доступных SMB папок на удаленном хосте Windows:

smbclient -L //192.168.31.33 -N

Если в Windows запрещен анонимный доступ, появится ошибка:

session setup failed: NT_STATUS_ACCESS_DENIED

В этом случае нужно указать учетную запись пользователя Windows, которую нужно использовать для подключения:

smbclient -L //192.168.31.33 -U User03

Если нужно использовать учетную запись пользователя домена, добавьте опцию –W:

smbclient -L //192.168.31.33 -U User03 –W Domain

smbclient вывести список общих папок на компьютере windows

Для интерактивного подключения к сетевой папке Windows используется команда:

smbclient //192.168.31.33/backup -U User03 -W Domain

или

smbclient //192.168.31.33/backup -U User03

Для анонимного доступа:

smbclient //192.168.31.33/backup -U Everyone

После успешного входа появится приглашение:

smb: \>

Вывести список файлов в сетевой папке:

dir

smbclient вывести список файлов в сетевой папке linux

Скачать файл из сетевой папки Windows:

get remotefile.txt /home/sysops/localfile.txt

Сохранить локальный файл из Linux в SMB каталог:

put /home/sysops/localfile.txt  remotefile.txt

Можно последовательно выполнить несколько команд smbclient:

$ smbclient //192.168.31.33/backup -U User03 -c "cd MyFolder; get arcive.zip /mnt/backup/archive.zip"

Полный список команд в smbclient можно вывести с помощью команды help. Команды smbclient схожи с командами ftp клиента.

При использовании команды smbclient может появиться ошибка:

Unable to initialize messaging contextsmbclient: Can't load /etc/samba/smb.conf - run testparm to debug it.

Чтобы исправить ошибку, создайте файл /etc/samba/smb.conf.

Если на хосте Windows отключен протокол SMB 1.0, то при подключении с помощью smbclient появится ошибка:

Reconnecting with SMB1 for workgroup listing.
protocol negotiation failed: NT_STATUS_CONNECTION_RESET
Unable to connect with SMB1 -- no workgroup available.

Обновлено:
Опубликовано:

Используемые термины: CIFS, Linux.

Протокол CIFS (SMB) позволяет работать с общими папками. В инструкции будет рассказано, как в системах на базе Linux можно настроить клиент для подключения к файловому серверу, который работает по данному протоколу.

Подготовительная работа
Синтаксис mount
Ручное монтирование
Автоматическое монтирование
Примеры
Дополнительная информация

Подготовка

Установка пакетов

Для монтирования общей папки необходимо установить набор утилит для работы с CIFS (в противном случае, мы получим ошибку mount.cifs команда не найдена).

а) Для систем RPM (РЕД ОС, Rocky Linux, CentOS):

yum install cifs-utils

б) Для DEB-систем (Astra Linux, Debian, Ubuntu):

apt update

apt install cifs-utils

Сетевые порты

Если мы будем монтировать сетевую папку, сервер которой находится за брандмауэром, необходимо открыть следующие порты:

  • 137/UDP
  • 138/UDP
  • 139/TCP
  • 445/TCP

Данные команды нет необходимости выполнять на клиентах. Только на стороне сервера.

В зависимости от используемого типа фаервола, команды будут отличаться.

а) iptables (как правило, на системах DEB):

iptables -I INPUT -p tcp —dport 445 -j ACCEPT

iptables -I INPUT -p udp —dport 137:138 -j ACCEPT

iptables -I INPUT -p tcp —dport 139 -j ACCEPT

Применяем настройки:

apt install iptables-persistent

netfilter-persistent save

б) firewalld (как правило, на системах RPM):

firewall-cmd —permanent —add-service=samba

firewall-cmd —reload

Синтаксис

mount.cifs <папка на сервере> <во что монтируем> <-o опции>

* вместо mount.cifs можно написать mount -t cifs.

Пример:

mount.cifs //192.168.1.1/public /mnt

* простой пример монтирования папки public на сервере 192.168.1.1 в локальный каталог /mnt.

Если нам не известны расшаренные папки на сервере, мы можем воспользоваться утилитой smbclient. Для начала установим ее.

а) на RPM (Rocky Linux / РЕД ОС / Red Hat / CentOS / Fedora):

yum install samba-client

б) на Deb (Debian / Ubuntu / Astra Linux / Mint):

apt install samba-client

Теперь вводим:

smbclient -L 192.168.1.1

или, при необходимости авторизоваться на файловом сервере:

smbclient -L 192.168.1.1 -U username

Ручное монтирование

Теперь монтирование можно выполнить следующей командой:

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

Для начала создаем файл, в котором будем хранить данные авторизации при подключении к общей папке:

vi /root/.smbclient

И добавляем в него данные следующего вида:

username=dmosk
password=dPassw0rd
domain=dmosk.local

* в этом примере создана пара логин/пароль — dmosk/dPassw0rddomain указывать не обязательно, если аутентификация выполняется без него.

Задаем права на созданный файл, чтобы доступ был только у пользователя, скажем, root:

chmod 600 /root/.smbclient

chown root:root /root/.smbclient

Теперь открываем конфигурационный файл fstab:

vi /etc/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: файл, который мы создали на предыдущем шаге.

Чтобы проверить правильность настроек, вводим следующую команду:

mount -a

Примеры использования опций

Версии 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

или в fstab:

//192.168.1.10/share    /mnt    cifs    guest    0 0

Для монтирования шары Windows, иногда, недостаточно указать опцию guest. Нужно делать так:

mount.cifs //192.168.1.10/share /mnt -o user=guest,pass=»

Или в fstab:

//192.168.1.10/share    /mnt    cifs    guest,pass    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 <имя группы>.

Читайте также

Дополнительная информация по теме:

1. Как во FreeBSD примонтировать CIFS.

2. Как настроить автоматическое монтирование дисков в системах Linux.

3. Установка и настройка файлового сервера Samba на Ubuntu или Debian.

4. Установка и настройка файлового сервера Samba на CentOS.

5. Пример скрипта для создания резервной копии файлового сервера.

Иногда, при организации совместных сетей между Windwos и Linux системами, в последних может появиться необходимость монтирования расшаренных SMB-ресурсов прямо к файловой системе. Прежде всего такая необходимость появляется при использовании легковесных рабочих сред (XFCE, OpenBox, LXDE и др), файловые менеджеры которых не поддерживают прямой доступ к samba.

Например, в среде Gnome доступ к ресурсу Windows можно получить прямо из файлового менеджера Nautilus, введя в адресной строке путь вида smb://192.168.0.11/ (где вместо необходимого ip-адреса также может быть просто указано сетевое имя windows-системы). Но многие другие файловые менеджеры (к примеру, быстрый и удобный PCMan File Manager до определённой версии) не поддерживают такой возможности, поэтому универсальным решением становится монтирование SMB к конкретному пути вашей файловой системы, в результате вы получите доступ к расшаренному ресурсу удаленной системы точно так же, как вы его получаете к своим дискам. Для этой цели нам потребуется установленный пакет cifs-utils, в Ubuntu и Debian установить его можно командой:

sudo apt-get install cifs-utils

В Fedora, CentOS и других RedHat based дистрибутивах:

sudo yum install cifs-utils

Также, как заметили в комментариях, рекомендуется установить пакеты ntfs-3g и ntfs-config, если они у вас ещё не установлены.

Теперь для начала давайте разберем как монтировать расшаренные папки вручную. Потребуется создать путь куда будем монтировать SMB-папку, пусть это, к примеру, будет /media/sharefolder:

sudo mkdir /media/sharefolder

Вот такой командой можно примонтировать папку, требующую авторизации по логину и паролю:

sudo mount -t cifs //192.168.0.11/share /media/sharefolder -o username=windowsuser,password=windowspass,iocharset=utf8,file_mode=0777,dir_mode=0777

где вместо //192.168.0.11/share – ip-адрес и имя необходимой общей папки (если имя расшаренной папки содержит пробел, то необходимо заключить весь путь в кавычки, как это показано в следующем примере), /media/sharefolder – путь куда будет монтироваться ресурс, windowsuser – имя пользователя с необходимыми правами доступа к этому ресурсу Windows, windowspass – пароль этого пользователя.

Если необходимая папка не требует обязательной авторизации, то подключить ресурс можно такой командой:

sudo mount -t cifs "//192.168.0.11/общие документы" /media/sharefolder -o guest,rw,iocharset=utf8,file_mode=0777,dir_mode=0777

Если гостевой доступ к необходимой папке включен только в режиме чтения, то будет достаточно такой команды:

sudo mount -t cifs //192.168.0.11/общие /media/sharefolder -o guest,iocharset=utf8

При удачном выполнении этих команд не должно произойти никакого уведомления – можете смело проверять как примонтировалась папка перейдя по вашему пути (в нашем примере – /media/sharefolder).
Отмонтируется папка командой:

sudo umount /media/sharefolder

Для того чтобы осуществить автомонтирование таких папок нам придется отредактировать системный файл fstab. Также, если доступ к необходимому windows-ресурсу требует обязательной авторизации, то потребуется предварительно создать файл, в котором будут прописаны логин и пароль доступа (сделать это можно текстовым редактором nano):

sudo nano /root/.smbcredentials

В этот новый файл добавьте две строки:

username=windowsuser
password=windowspass

где, соответственно, windowsuser – имя пользователя с необходимыми правами доступа к ресурсу Windows, windowspass – пароль этого пользователя. Измените права созданного файла так, что редактировать и смотреть его смог только root, то есть сама система:

sudo chmod 700 /root/.smbcredentials

Сохраните изменения и переходите к редактированию файла /etc/fstab:

sudo nano /etc/fstab

И здесь в самом конце добавьте строку типа:

//192.168.0.11/share /media/sharefolder cifs credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0777,dir_mode=0777 0 0

Если авторизации по имени и паролю не требуется, а требуется только гостевой доступ, то создавать файл .smbcredentials не потребуется, этот шаг можно было пропустить и сразу в /etc/fstab добавить строку:

//192.168.0.11/общие\040документы /media/sharefolder cifs guest,rw,iocharset=utf8,file_mode=0777,dir_mode=0777 0 0

Обратите внимание, что здесь если ваша папка содержит пробелы, то вариант аналогичный командной строке – заключении пути в кавычки – не поможет, для того, чтобы fstab понял пробелы – их необходимо заменить на четыре символа: \040
И, соответственно, если требуется только лишь гостевой доступ в режиме чтения к windows-папке, то будет достаточно такой строки:

//192.168.0.11/общие /media/sharefolder cifs guest,iocharset=utf8 0 0

Для того, чтобы проверить корректно ли монтируется shared-папка из fstab без перезагрузки нужно выполнить такую команду:

sudo mount -a

Также к этому стоит добавить, что если вы хотите получать доступ к windows-шаре не через ip-адрес, а через имя машины, то вам потребуется установить winbind, в Debian-based:

sudo apt-get install winbind

Или в RedHat-based системах:

sudo yum install samba-winbind

После этого отредактируйте файл /etc/nsswitch.conf:

sudo nano /etc/nsswitch.conf

Где в строке:

hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4

перед dns добавьте wins, то есть после редактирования она должна выглядеть вот так:

hosts: files mdns4_minimal [NOTFOUND=return] wins dns mdns4

После перезагрузки для получения доступа к windows-ресурсу через CIFS можно будет указывать не только ip, но и сетевое имя windows-ресурса (netbios name). Но мы всеже рекомендуем использовать непосредственно ip-адрес (как было описано в статье) – к нему обращение идет напрямую, быстрее.

Также стоит отметить, что таким образом можно монтировать только конкретные общие папки (например: //192.168.0.11/share), но не весь windows-ресурс целиком (то есть просто: //192.168.0.11).

In the Windows operating system, there is a feature called file sharing. On one computer, you can set up windows-shared folder that will be accessible to all computers on the local network. This is done using the SMB protocol, which has several versions. In Linux, you can open and create shared folders using Samba.

The Samba server supports all versions of the SMB protocol. However, there are some compatibility issues. In this article, I will explain how to access a Windows Shared folder in Linux using popular desktop environments and the command line.

Table of Contents

  • Why It May Not Work?
  • Ensure that Everything is Set Up Correctly in Windows
  • Finding Shares in Linux Terminal
  • Open Shared Folder in KDE Dolphin
  • Open Share in GNOME Nautilus
  • Mounting a Shared Folder in the Terminal
  • Wrapping Up

Why It May Not Work?

In older versions of Linux distros and Windows 7 everything worked fine because they used the SMB1 protocol. However, there have been several changes recently. In 2017, the Wannacry virus emerged, which exploited vulnerabilities in the SMB1 protocol. As a result, modern versions of Windows have disabled support for SMB1 and now use SMB3 by default. Samba has also disabled SMB1 since version 4.11. However, SMB2 and SMB3 lack support for device discovery in the local network.

In general, this is no longer necessary because there is a network discovery protocol called Zeroconf. In Linux, its open-source implementation, Avahi, is used. Linux servers and NAS storage can publish themselves on the local network using this protocol. So that, there is no need to support it in SMB. However, Microsoft decided to use its own protocol called WS-Discovery, and that’s where the problems began.

At the time of writing this article, Linux system has issues with discovering shared folders in the local network. The Nautilus file manager in GNOME does not support WS-Discovery at all, and there are no production-ready terminal utilities for it either. You can track the current status of implementing WS-Discovery support in this GVFS issue. However, in 2020, the KDE team added support for this protocol in the Dolphin file manager using kdsoap-ws-discovery-client.

Later, a program for KDE called Smb4k appeared, which can discover network resources using Avahi and the WS-Discovery protocol, but it needs to be compiled with a special option. So that, in GNOME, you can only open a Windows shared folder by knowing the IP address of the computer where it is located. Whereas in KDE, it is a bit more convenient to do so.

Ensure that Everything is Set Up Correctly in Windows

Previously, it was enough to go to File Explorer and enable file sharing there. But it no longer works that way. First, you need to make your current network private in Windows. By default, only private networks are considered secure, and Windows machines can be discovered in them. To do this, open Settings -> Network & Internet -> Ethernet and select Network Profile Type -> Private Network:

If your current network is wireless, you should do the pretty same thing. Next, go back and select Advanced Sharing Settings. In this window, enable Network discovery and File and printer sharing:

Finally, you need to ensure that the firewall is configured correctly and allows SMB connections. To do this, go back to the main Settings menu, then open Privacy & Security -> Firewall & network protection. Click on Allow an app through the firewall:

Make sure that File and printer sharing and Network discovery are enabled for Private networks:

That’s it. Now you can go to your Linux machine.

Although there are no command-line tools for working with WS-Discovery, you can try to find devices with shared resources using Nmap. This program cannot search for resources like Avahi does, but it can help you find IP addresses with an open port 445. This port is used by SMB. To do this, you need to install the following packages (Ubuntu):

sudo apt install nmap smbclient

Or Fedora:

sudo dnf install nmap samba-client

Also, you need to find out the IP address range of your local network. You can take your IP address and mask and just replace the fourth digit with zero. For example:

ip -br a

The command for the search will look like this. Replace 192.168.124.0/24 with your local network address range and run it in the the terminal window with sudo privileges:

nmap -p 445 --open -n -Pn 192.168.124.0/24

The -p option specifies the port 445, -Pn option disables ICMP discovery and treats all IP addresses as alive, -n disables DNS hostname resolution. The command may take quite a while, but as a result, it will find hosts with open port 445 if such hosts exist in your local network:

This can’t be considered as normal network discovery, but it works. Now you can use smbclient to see which shared folders are on the server that you found. For example:

smbclient -L 192.168.124.63

The command will ask you to enter the share password. Usually, it is password for your Windows user, and then it will show all available shared folders:

Now let’s have a look at how to mount them.

To open a shared folder in KDE, you can use the Dolphin file manager. As I mentioned earlier, here you can see all available computers that have network drive on the local network. To do this, run Dolphin, then open Network, and then Shared Folders (SMB):

Click on one of the resources and enter the username and password to view the available folders:

This is what shared folders from Windows 11 look like. Here you can find windows files:

If network discovery does not work in your case, you can still enter the IP address of the resource in the text field at the top of the window and connect to it. For example, smb://192.168.124.63/

If you want to connect to a Windows shared folder in the GNOME graphical interface, you can use the Nautilus file manager. Open Other Locations and find at the bottom of the window the inscription Connect to Server and a field for entering an address.

There’s no point in opening the Windows Network item, because GVFS, which is used in GNOME for disk mounting, does not support the WS-Discovery protocol. To connect to a remote windows share located on a server with IP 192.168.124.63, enter this address and press the Connect button:

smb://192.168.124.63

In the next window, you need to enter a password and after that, you can view the files of the shared folder:

After this, you can browse your windows folders.

Additionally, you can use a shortcut on the left panel to access a remote share which is already mounted.

If you want to mount windows share in the terminal, you can use cifs-utils and the mount command. Firstly, install the cifs-utils package. The command for Ubuntu:

sudo apt install cifs-utils

In Fedora:

sudo dnf install cifs-utils

Now, you can execute the mount command specifying the cifs file system type and the username option. Note that you can’t mount the root of the cifs share, you need to add any folder in the path. For example, Users on 192.168.124.63:

sudo mount -t cifs -o username=losst //192.168.124.63/Users /mnt/

If you want to have write access to the windows share folder, you need to add the uid option with the identifier of your user. For the first user, it’s usually 1000:

sudo mount -t cifs -o username=losst,uid=1000 //192.168.124.63/Users /mnt/

You can find the identifier of the current user in the UID environment variable:

echo $UID

If you want to mount share automatically at system startup, you need to save the share username and password in a credentials file, for example, /etc/share/windows-credentials. For instance:

sudo mkdir -p /etc/share/

username=losst
password=password
domain=workgroup

And then add the following line to the /etc/fstab file:

//192.168.124.63/Users /mnt/share cifs credentials=/etc/share/windows-credentials,uid=1000,nofail 0 0

The nofail option is needed to allow your computer to boot even if the remote folder could not be mounted. After this, reload systemd settings:

sudo systemctl daemon-reload

Create the mount point directory:

sudo mkdir -p /mnt/share

You can check that everything is working using the following command:

sudo mount /mnt/share

If everything is ok, you could see contents of mounted share in the /mnt/share folder:

Wrapping Up

In this article, we looked at how to mount Windows network share in Linux using a graphical interface or in the terminal. Despite some difficulties, this can be used quite effectively. Do you know any other applications or scripts which can help with that? Share their names in the comments section below.

The article is distributed under Creative Commons ShareAlike 4.0 license. Link to the source is required.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 10 pro serial key
  • Node js pm2 windows
  • Windows repair all in one usb
  • Windows не удается подключиться к принтеру 0x0000000a windows
  • Компьютер долго включается что делать для windows 10