Обновлено:
Опубликовано:
Используемые термины: 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/dPassw0rd; domain указывать не обязательно, если аутентификация выполняется без него.
Задаем права на созданный файл, чтобы доступ был только у пользователя, скажем, 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. Пример скрипта для создания резервной копии файлового сервера.
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.
В этой статье мы рассмотрим, как в 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 для подключения к сетевой папке.
При подключении сетевой 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 в качестве владельца файлов в папке
По умолчанию шары 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
Для интерактивного подключения к сетевой папке 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
Скачать файл из сетевой папки 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.
Needs Updating |
Please see https://launchpad.net/bugs/1244123 about one reason for the update need.
MountSAMBAshareFSTAB
Contents
-
Introduction
- Two methods, depending on share host
- Prerequisites
-
Setup
- Single User
- Multiple Users
- Credentials File
- Editing fstab
- Ensure
- Completing Setup
-
Troubleshooting
- cifs will not mount
- Server is down, filesystem is hung
- CIFS remote ownership enforcement
- System Hangs on Shutdown
- Login without Credentials
- Connect when network available
This page is being developed to fix a dead link on the InternetAndNetworking page.
Introduction
This guide will show you how to setup a mount of a remote windows share, and have it always there when you startup.
- cifs
- smbfs
smbfs is the «original» method.
However, smbfs is not compatible with security signatures, which are enabled by default and not recommended to disable on Windows Server 2003 and later. If a share is served by Windows Server 2003 or later, you should use cifs.
Prerequisites
You must have a windows machine (or other machine running Samba) with an accessible share.
The ‘samba’ package itself is not necessary if you only need a smb client.
The package providing the tools needed to mount «smbfs» and «cifs» filesytems is «smbfs» (up to 10.04) or «cifs-utils» (10.10 onwards). You may have smbfs installed on your machine. If not, run
sudo apt-get install smbfs
…or…
sudo apt-get install cifs-utils
…as appropriate.
Update the unmount order to prevent CIFS from hanging during shutdown.
sudo update-rc.d -f umountnfs.sh remove sudo update-rc.d umountnfs.sh stop 15 0 6 .
Setup
Single User
Note the UID of the single user which is to have access to the share. For a user named $username, the following command outputs the UID
grep $USER /etc/passwd | cut -d: -f3
Multiple Users
If multiple users are to have the same level of access to the share, then create a new user group, presumably named after the share.
Navigate to «System» -> «Administration» -> «Users and Groups» -> «Manage Groups». -> «Add Group» and select a name, Group ID (GID), and group members. Note the GID — you will need it later.
Credentials File
Warning- this method is not completely secure, any user with root access could see your password in plain text.
Create a file called .smbcredentials, probably in the home directory of the primary user of the share. In this file put username an equals sign and the windows username (and domain if loging into a domain) on the first line, put password an equals sign and the password for that user account on the second line of the file. The file should look like:
username=MyUsername password=MyPassword # OR: # username=MyUsername@MyDomain # password=MyPassword # OR: (for cifs on Windows Serve 2003) # username=MyDomain/MyUsername # password=MyPassword
On the command line, in the directory of .smbcredentials type
sudo chown root .smbcredentials sudo chmod 600 .smbcredentials
this will ensure that only root can access this file.
Note: Regretfully as from version 3.3.2-1ubuntu3.2 (October 2009) this approach is no longer possible together with the «user» option. A security fix prevents reading the credentials file if you don’t have read access to it. You will have to pin the packages at version 3.3.2-1ubuntu3 or 3.3.2-1ubuntu3.1 to continue using this approach as non-root.
Editing fstab
Warning- editing the fstab file can be dangerous, please back it up before continuing.
Note: if servername or sharename has a literal space (i.e. ‘ ‘), substitute \040 instead, so that ‘server name’ becomes ‘server\040name’
Add a line at the bottom of your /etc/fstab file that specifies:
//$SERVER/$SHARE $MOUNTPOINT $FS_TYPE credentials=$SMB_CREDENTIALS,uid=$UID,gid=$GID
# e.g. SERVER=apollo SHARE=install_files MOUNTPOINT=/path/to/mnt FS_TYPE=smbfs SMB_CREDENTIALS=/path/to/.smbcredentials UID=1000 GID=1000
smbfs, group perms
- FS_TYPE=smbfs
- GID=1234 # the newly created group’s ID
- don’t include uid=$UID, which defaults to that of root
//apollo/install_files /path/to/mnt smbfs iocharset=utf8,credentials=/path/to/.smbcredentials,gid=1234 0 0
Note: many directories are set so that only the user can write to the directory and that the group can only read (permissions 0755), if this is the case then when it is mounted the group will still not be able to write to the directory regardless of their permission on the share. To give the group write permissions on the mount then use the following.
//apollo/install_files /path/to/mnt smbfs iocharset=utf8,credentials=/path/to/.smbcredentials,dir_mode=0775,gid=1234 0 0
smbfs, user perms
- FS_TYPE=smbfs
- UID=1000 # particular user’s uid
- don’t include gid=$GID, which defaults to $UID
//apollo/install_files /path/to/mnt smbfs iocharset=utf8,credentials=/path/to/.smbcredentials,uid=1000 0 0
cifs, group perms
- FS_TYPE=cifs
- GID=1234 # the newly created group’s ID
- don’t include uid=$UID
//apollo/install_files /path/to/mnt cifs iocharset=utf8,credentials=/path/to/.smbcredentials,gid=1234 0 0
Note: many directories are set so that only the user can write to the directory and that the group can only read (permissions 0755), if this is the case then when it is mounted the group will still not be able to write to the directory regardless of their permission on the share. To give the group write permissions on the mount then use the following.
//apollo/install_files /path/to/mnt cifs iocharset=utf8,credentials=/path/to/.smbcredentials,dir_mode=0775,gid=1234 0 0
cifs, user perms
- FS_TYPE=cifs
- UID=1000 # the user’s uid
- don’t include gid=$GID
//apollo/install_files /path/to/mnt cifs iocharset=utf8,credentials=/path/to/.smbcredentials,uid=1000 0 0
Ensure
- The entire expression MUST all be on one line in your fstab file
- use «//» and «/» instead of «\\» and «\» when specifying the share location
- /path/to/mnt is a directory that exists (and is empty)
Completing Setup
Reload fstab:
sudo mount -a
Troubleshooting
cifs will not mount
Note:- cifs by default does not resolve netbios names so you may get an error message when you try to mount that the name could not be resolved into an address and «could not find target server». In order to enable netbios resolution you need to edit /etc/nsswitch.conf and add the winbind package:
- edit /etc/nsswitch.conf
sudo gedit /etc/nsswitch.conf
change the line from
hosts: files dns
to
hosts: files wins dns
- next install winbind
sudo aptitude install winbind
Now you should be able to mount the directory.
Note: If you experience slow dns resolution after making these changes, you can change the order of the entries to the following and you may see an improvement.
hosts: files dns wins
Server is down, filesystem is hung
If the client somehow loses contact with the Samba server, then the filesystem will probably get hung. Basically, it becomes a blackhole, eating things that try to read to/write from it (e.g. ls) and refusing to go away (e.g., umount says that the «device is busy»).
Sometimes, all you need to do is restart the Samba daemon on the server machine.
sudo /etc/init.d/samba restart
If that doesn’t work, or for some reason you can’t do anything on the server side, then try
sudo umount -lf /mount/point
The -f option forces (possibly unclean) unmounting, and the -l option is for «lazy unmounting», and seems to work around «device is busy» errors that occur with just -f.
CIFS remote ownership enforcement
When you connect using CIFS to a server which supports Unix permissions (e.g. Samba), CIFS will by default try to enforce remote Unix ownership UIDs and Unix permissions when you try to access the share. i.e. if a file is owned by UID 502 on the remote server, then the local kernel will try to enforce the same permissions if it were owned by UID 502 on the local machine. Note: This has nothing to do with the remote server’s security settings. This is an extra local ownership enforcement by the filesystem driver. It is a feature to allow use of remote share as a local drive with full Unix permissions enforcement if users match.
But if this is a public share, then chances are, the remote UIDs will not make sense locally. A remote UID might be a completely different user or might not exist at all on the local machine. If remote UIDs and local UIDs do not match, then local users will have trouble using the share. To disable this, use the «noperm» mount option. Remote permissions and UIDs will still be visible, but they will not be enforced locally.
System Hangs on Shutdown
Sometimes during shutdown, networking will be turned off before the network share is unmounted. This will cause the computer to display the below code for a few minuets before shutting down (the numbers seem to change after each boot).
CIFS VFS: server not responding CIFS VFS: no response for cmd ## mid ###
To fix this problem, and allow the computer to shut down smoothly, just change when the network share is unmounted by the file system. This can be done by running the following commands:
sudo update-rc.d -f umountnfs.sh remove sudo update-rc.d umountnfs.sh stop 15 0 6 .
A better solution for those using Gnome: http://ubuntuforums.org/showthread.php?t=1347340
Login without Credentials
If you want to mount the share without the credentials file you can use the entry below. I believe that by adding the _netdev in the entry below, it will not mount the share if you are not connected to the same network that the share is on or if you are not connected to a network at all.
- # /etc/fstab: static file system information. #
# <file system> <mount point> <type> <options> <dump> <pass>
//<server>/<share> <mount point> cifs rw,_netdev,user=<username>,password=<password>,uid=<uid>,gid=<gid> 0 0
Here is an example of the last line //gurnee/projects /home/jcrow/GurneeServer cifs rw,_netdev,user=DOMAIN/user,password=password,uid=1000,gid=100 0 0
The server being connected to is Gurnee, the shared folder is projects, the mount point is /home/jcrow/GurneeServer
Connect when network available
The _netdev option is also used for systems that only have networking started at user login (as when using the Gnome Network Manager package). For having network connections enabled at boot up (without requiring a user login) then tools that write to the /etc/network/interfaces file may have to be used. It is probably good policy to always use _netdev for all automatic network mounts.
MountWindowsSharesPermanently (last edited 2015-07-18 16:35:39 by 5g3-steven-7tv)
In this article, we’ll look at how to mount a shared network folder hosted on a Windows computer in Linux. Windows uses the SMB (Server Message Block) protocol, formerly known as CIFS (Common Internet File System) to share and access shared folders over the network. On Linux, you can use the cifs-utils or Samba client to access Windows network shares via SMB protocol.
Hint. Port TCP/445 is used to access the shared network folder via SMB/CIFS. UDP ports 137, 138, and TCP ports 139 are used for name resolution. If these ports are closed, you will only be able to connect to a shared folder on Windows by using a host IP address.
You can mount a shared folder hosted on a Windows computer using the tools in the cifs-util package. Run this command to install the package:
- Ubuntu/Debian:
$ sudo apt-get install cifs-utils
- CentOS/Oracle/RHEL:
$ sudo dnf install cifs-utils
Create a mount point:
$ sudo mkdir /mnt/share
You can now mount the SMB share from a Windows computer using the User03 account:
$ sudo mount.cifs //192.168.31.33/backup /mnt/share -o user=User03
You must have a Windows user password to connect to a shared folder.
You can set additional parameters when mounting a network SMB folder:
$ 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 – shared network folder in Windows;
- /mnt/share – mount point;
- -t cifs – specify the type of file system to mount;
- -o mount options (this option can only be used as root, so sudo is used in the command above);
- username=User03,password=PasswOrd1 – Name and password of the Windows user who has permission to access the share. If anonymous access to the network folder is allowed on Windows, you can specify the guest username here;
- iocharset=utf8 – enable support for UTF8 encoding to display the name of files on SMB shares;
- uid=1000 – use this Linux user as the owner of the files in the mounted folder.
By default, Windows shares will be mounted on Linux with full permissions (0755). Add the following options to the command if you want to change the default mount permissions:
dir_mode=0755,file_mode=0755
Add the following line to the /etc/hosts file if you want to use the computer name instead of the IP address when mounting a Windows share:
IP_ADDRESS HOSTNAME
If you do not want to enter Windows user credentials in the mount command, you can save them to a file.
For example:
$ mcedit ~/.windowscredentials
Insert into the file:
username=User03
password=PasswOrd1
If you need to use a user account from an Active Directory domain, you will need to add a third line to the file:
domain = poweradm.com
To anonymously mount a Windows folder:
username=guest
password=
Change file permissions:
$ chmod 600 ~/.windowscredentials
When mounting a shared folder, you can now specify the file path instead of the plaintext credentials:
$ sudo mount -t cifs -o credentials=/home/sysops/.windowscredentials,uid=1000,iocharset=utf8 //192.168.31.33/backup /mnt/share
Unmount a shared SMB folder:
$ sudo umount /mnt/share
Automatically Mount Network SBM Shares on Linux
The /etc/fstab file can be used to enable the automatic mounting of a Windows-shared folder on Linux.
$ sudo mcedit /etc/fstab
Add the following string to the file to connect the SMB shared folder:
//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev 0 0
- rw – mount SBM folder in read/write mode
- nofail – resume Linux boot if file system mount fails
- _netdev – indicates that the filesystem is network connected. Linux will not mount such filesystems until networking has been successfully initialized on the host.
You can specify the version of the SMB protocol to be used for the connection (SMB version 1.0 is insecure and disabled by default in modern Windows versions). Add the parameter vers=3.0 to the end of the cifs connection string.
//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev,vers=3.0 0 0
If an incompatible (old version) of SMB is used on the remote Windows host, a connection error will occur:
mount error(112): Host is down
or
mount error(95): Operation not supported
To immediately mount a shared folder from the fstab configuration file
$ mount -a
How to Access Windows Share on Linux with a Samba Client
Install the samba-client on Linux:
- Ubuntu/Debian:
$ sudo apt-get install smbclient
- CentOS/Oracle/RHEL:
$ sudo dnf install smbclient
To view the SMB hosts on the local network:
$ smbtree -N
List the SMB folders that are available on a remote Windows host:
$ smbclient -L //192.168.31.33 -N
If you have disabled anonymous access in Windows, you will get an error:
session setup failed: NT_STATUS_ACCESS_DENIED
In this case, you must specify the Windows user account that you want to use to access the shared folder:
$ smbclient -L //192.168.31.33 -U User03
Add the -W option if you want to use a domain user account:
$ smbclient -L //192.168.31.33 -U User03 –W Domain
To establish an interactive connection to a Windows network share, use the following command
$ smbclient //192.168.31.33/backup -U User03 -W Domain
or
$ smbclient //192.168.31.33/backup -U User03
To access the SMB folder anonymously:
$ smbclient //192.168.31.33/backup -U Everyone
After logging in, the following prompt will appear:
smb: \>
List the files in a shared SMB folder:
dir
Download the file from the Windows shared folder:
get remotefile.txt /home/sysops/localfile.txt
Save a local file from Linux to an SMB directory:
put /home/sysops/localfile.txt remotefile.txt
You can run multiple smbclient commands one after the other:
$ smbclient //192.168.31.33/backup -U User03 -c "cd MyFolder; get arcive.zip /mnt/backup/archive.zip"
You can use the help command to display a full list of commands in smbclient. The syntax of the smbclient commands is similar to the ftp client commands.
An error may occur when using the smbclient command:
Unable to initialize messaging context
smbclient: Can't load /etc/samba/smb.conf - run testparm to debug it.
Create the file /etc/samba/smb.conf to fix the error.
If the SMB 1.0 protocol is disabled on the Windows host, the smbclient connection will fail:
Reconnecting with SMB1 for workgroup listing.
protocol negotiation failed: NT_STATUS_CONNECTION_RESET
Unable to connect with SMB1 -- no workgroup available.