- Как смонтировать общий ресурс Windows в Linux с помощью CIFS
- Установка пакетов утилит CIFS
- Монтирование общего ресурса CIFS Windows
- Автоматический монтаж
- Отключение общего ресурса Windows
- Выводы
- How to Mount a Windows Share in Linux
- SMB vs CIFS vs SAMBA
- Mount a Windows Share Using GUI (Files / Nautilus)
- Mount A Windows Share Using Command Line
- Using the mount.cifs Command
- Automatically Mount CIFS Share at Boot
- Mount CIFS Share at Boot Using /etc/fstab
- Mount CIFS Share using AutoFS
- Installing autofs Package
- Create Credentials File
- Get UID for User
- Edit auto.master Map File
- Create the Shares File
- Restart the Service
- Test and Verify
- Conclusion
- Linux mount windows shared folder
- Установка CIFS
- Монтируем Windows Share (сетевой ресурс)
- Безопасность учетных данных при монтировании через CIFS
- Как сделать автоматическое монтирование общей папки Windows
- Как размонтировать общую папку CIFS
- Автор
- Возможно Вам будет это инетересно
- Как инвертировать совпадение по grep
- Как посмотреть список пользователей Linux
- Конфигурация файла .gitignore в Git
- 7 thoughts on “Как подключить общую папку (сетевой ресурс, шару) Windows к Linux”
Как смонтировать общий ресурс Windows в Linux с помощью CIFS
В операционных системах Linux и UNIX общий ресурс Windows можно cifs к определенной точке монтирования в локальном дереве каталогов с cifs опции cifs команды mount .
Common Internet File System (CIFS) — это сетевой протокол обмена файлами. CIFS — это форма SMB.
В этом руководстве мы объясним, как вручную и автоматически монтировать общие ресурсы Windows в системах Linux.
Установка пакетов утилит CIFS
Чтобы смонтировать общий ресурс Windows в системе Linux, сначала необходимо установить пакет утилит CIFS.
Установка утилит CIFS в Ubuntu и Debian:
Установка утилит CIFS на CentOS и Fedora:
Имя пакета может отличаться в зависимости от дистрибутива Linux.
Монтирование общего ресурса CIFS Windows
Подключение удаленного общего ресурса Windows аналогично монтированию обычных файловых систем.
Сначала создайте каталог, который будет точкой монтирования для удаленного общего ресурса Windows:
Выполните следующую команду от имени пользователя root или пользователя с привилегиями sudo, чтобы смонтировать общий ресурс:
Вам будет предложено ввести пароль:
В случае успеха вывод не производится.
Чтобы убедиться, что удаленный общий ресурс Windows успешно смонтирован, используйте команду mount или df -h .
После монтирования общего ресурса точка монтирования становится корневым каталогом смонтированной файловой системы. Вы можете работать с удаленными файлами, как если бы они были локальными.
Пароль также можно указать в командной строке:
Если пользователь находится в рабочей группе или домене Windows, вы можете установить его следующим образом:
Для большей безопасности рекомендуется использовать файл учетных данных, который содержит имя пользователя, пароль и домен общего ресурса.
Файл учетных данных имеет следующий формат:
Файл не должен быть доступен для чтения пользователям. Чтобы установить правильные разрешения и владение , запустите:
Чтобы использовать файл учетных данных, определите его следующим образом:
По умолчанию подключенный общий ресурс принадлежит пользователю root, а права доступа установлены на 777.
Используйте параметр dir_mode чтобы установить права file_mode к каталогу, и file_mode чтобы установить права file_mode к файлу:
Владение пользователем и группой по умолчанию можно изменить с помощью параметров uid и gid :
Чтобы установить дополнительные параметры , добавьте их в виде списка, разделенного запятыми, после параметра -o . Чтобы получить список всех параметров монтирования, введите в терминале man mount .
Автоматический монтаж
Когда общий ресурс монтируется вручную с помощью команды mount , он не сохраняется после перезагрузки.
Файл /etc/fstab содержит список записей, определяющих, где, как и какая файловая система будет монтироваться при запуске системы.
Чтобы автоматически монтировать общий ресурс Windows при запуске системы Linux, определите монтирование в /etc/fstab . Строка должна включать имя хоста или IP-адрес ПК с Windows, имя общего ресурса и точку монтирования на локальном компьютере.
Добавьте в файл следующую строку:
Выполните следующую команду, чтобы смонтировать общий ресурс:
Команда mount прочитает содержимое /etc/fstab и смонтирует общий ресурс.
В следующий раз, когда вы перезагрузите систему, общий ресурс Windows будет подключен автоматически.
Отключение общего ресурса Windows
Команда umount отсоединяет (размонтирует) смонтированную файловую систему от дерева каталогов.
Чтобы отсоединить смонтированный общий ресурс Windows, используйте команду umount за которой следует либо каталог, в котором он был смонтирован, либо удаленный общий ресурс:
Если для CIFS-монтирования есть запись в fstab , удалите ее.
Команда umount не сможет отсоединить общий ресурс, когда он используется. Чтобы узнать, какие процессы обращаются к общему ресурсу Windows, используйте команду fuser :
Как только вы найдете процессы, вы можете остановить их с помощью команды kill и отключить общий ресурс.
Если у вас все еще есть проблемы с —lazy ресурса, используйте параметр -l ( —lazy ), который позволяет вам отключить занятую файловую систему, как только она больше не будет занята.
Выводы
В Linux вы можете cifs к Windows с помощью команды mount с опцией cifs .
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
How to Mount a Windows Share in Linux
In this tutorial we will be discussing different ways to connect to a Microsoft share form Linux. Before we dive in I think it is important to understand the different terminology used when talking about Samba, SMB and CIFS shares.
Table of Contents
SMB vs CIFS vs SAMBA
SMB (Server Message Block) is a protocol used for network file sharing. It was originally designed at IBM in the 1980’s.
CIFS (Common Internet File System) is a implementation of SMB that was created by Microsoft.
SAMBA is an open source software suite and set of utilities used by UNIX/Linux to communicate with Microsoft Windows systems.
From the average user stand point SMB and CIFS can be used interchangeably. As you will see below, we will connect to the same share using both SMB and CIFS.
Mount a Windows Share Using GUI (Files / Nautilus)
You can easily connect to a Windows share using the Files application (formerly known as Nautilus) that ships with Gnome. For the sake of clarity, we will call it Nautilus.
Open the Nautilus application and select “Other Location” from the left places panel.
At the bottom of the screen you will see “Connect to Server” with a box asking for you to enter the server address. Inside that box is a diamond with a question mark in it that you can click for some help.
As you can see in the pop-up, server addresses are made up of a protocol prefix and an address. On my Windows machine named “MyMuse” I created a share called “SharedDocs”. So inside that entry box we will use:
We can also use the IP address:
This will bring up a dialog box asking for authentication credentials.
Select the “Registered User” radio button and enter your details. You have three options for storing your password.
- Forget password immediately – This will log you in and and soon as your session is over you will be required to provide your credentials again.
- Remember password until you logout – Remember your password until you explicitly logout.
- Remember forever – This option will store the credentials and allow you to easily return to the share.
Once you are connected, Nautilus will show the location on the left panel allowing easy access to the share.
Be aware that once that connection is closed you will have to go back to “Other Locations” and use the drop down box to reconnect. If you want to make the share persistently accessible from the left menu you will need to add a bookmark.
NOTE: If you do not want to type your credentials every time ensure that you select “Remember Forever” when authenticating to the share.
To add a bookmark, connect to the share then right click it in the left panel and select “Add Bookmark”.
If you have a lot of shares, or multiple shares on the same device, it will be hard to differentiate them. You can rename them to something more user friendly by right clicking on the bookmark and selecting “Rename…”.
Now we can easily navigate to our share as the name is clearly visible and easy to identify.
Mount A Windows Share Using Command Line
Using the mount.cifs Command
You can easily mount a cifs share from the command line using the mount.cifs command. Using the mount command requires root privileges.
First, create a directory to mount the share:
Use the mount.cifs command to mount the share at the created directory.
You can use the IP address as well.
Alternatively, you can use mount -t cifs with the same syntax.
Automatically Mount CIFS Share at Boot
Mount CIFS Share at Boot Using /etc/fstab
You can add your CIFS mount point in /etc/fstab and have the system mount it during boot. However, there are some considerations to make. If the share is not available at boot time the system will hang until the mount attempt times out, or worse, refuse to boot. This will cause a delay in accessing the system. To avoid this you can use autofs (next section). Also mounting it via fstab requires you to put your credentials somewhere in plain text. You have two options when using fstab to mount a CIFS share.
- Put the credentials in the fstab file itself – This is a huge security risk as fstab is readable by any user. Someone can simply cat the file and see your credentials. IT IS NOT RECOMMENDED!
- Use a credentials file – This entails saving your credentials in a separate file which can then be protected by permissions. Although your credentials will still be saved in plain text, someone would need root permissions to read them.
Because of the high risk of the first option, we will not even discuss how to do it. It is easy enough to use a credentials file.
First, create a hidden file in root’s home directory (/root/). You can call this file whatever you like. Most people call it .smbcreds or similar. In this file you need two lines, one containing “username= ” and one containing “password= ”.
Now set the permissions so it is only readable by root:
Now edit the /etc/fstab file and add the following information:
- Remote server share address (//mymuse/shareddocs)
- Local mount point (/mnt/cifs)
- Filesystem type (cifs)
- options (credentials file=/root/.smbcreds)
- dump option (0)
- check option (0)
Example fstab, last line showing the CIFS mount point.
Mount CIFS Share using AutoFS
The most obvious benefit of using autofs is that the share is only mounted when being accessed. If it is unavailable it will not effect your system when it boots.
Using autofs has the same credentials issues described above with fstab. It is also necessary to store your password in plain text when using autofs for cifs shares.
Installing autofs Package
Install autofs in CentOS 7, or Red Hat 7:
Install autofs in Ubuntu 18:
Let’s configure autofs to mount our Windows share.
Create Credentials File
First, ensure you create the credentials file as described above:
DO NOT forget to set the permissions:
Get UID for User
Now, let’s get our user accounts uid so we can tell autofs to mount the share as our user instead of root.
Edit auto.master Map File
Edit the /etc/auto.master configuration file. In this file we will provide a map of directories to shares for autofs to use. Add the following line to the file:
The first part of the above line is the directory we are using as a mount point (you can create a custom directory if you wish). The second is the file that autofs should look in for instructions on how to connect to the resource and mount it.
Create the Shares File
Next edit or create the /etc/auto.shareddocs file and add the following:
Restart the Service
Now we must restart the autofs service so it reads the new configuration.
Test and Verify
Now, let’s look in the /mnt directory.
The shareddocs directory doesn’t exist until you try to access it (auto fs). If everything above was followed, we should be to cd into that directory even though we do not see it. The directory will be dynamically created as it is accessed.
Bob’s your uncle.
Conclusion
In this article we covered 3 different ways to mount your Windows shares in Linux. You should now be able to mount an SMB share via the GUI, manually on the command line, automatically on boot and with autofs.
An important point I would like to stress is make sure you protect your credentials. I hope you enjoyed this tutorial, please leave feedback or questions in the comments below.
Linux mount windows shared folder
CIFS (Common Internet File System) — это популярный протокол обмена файлами в Интернете. Этот протокол и позволит пользователям ОС Linux получить доступ к общей папке Windows.
CIFS — это реализация SMB (Server Message Block) — протокола, используемого для совместного использования сетевых файлов. Но он устарел.
В этой статье мы по шагам пройдем все этапы установки и настройки CIFS, чтобы подключиться к сетевому ресурсу Windows на ОС Linux.
Установка CIFS
Сейчас мы установим пакет cifs-utils на Ubuntu Linux (точно так же можно сделать на всех Debain-подобных ОС).
Монтируем Windows Share (сетевой ресурс)
Сейчас мы разберем на примерах, как монтировать общую папку Windows вручную и автоматически.
Создадим на нашем Linux директорию, к которой мы будем монтировать сетевой ресурс. Назовем ее myshare и расположена она будет в каталоге /mnt
Сетевой ресурс (шара) Windows может быть примонтирован к ОС Ubuntu или Debian с помощью следующей команды:
WIN_HOST_IP — это IP адрес хоста Windows, на котором расположена общая папка
share — имя сетевого ресурса
user — наш пользователь и Passw0rd — пароль с которыми мы подключемся к шаре.
Если пользователь доменный, то необходимо в опциях (-o) указать домен.
По-умолчанию сетевой ресурс монтируется с полными правами (rwx или 777). Если Вы хотите установить иные права, используйте опции dir_mode и file_mode.
Так же Вы можете установить владельцев uid (id пользователя) и gid (id группы).
Если после выполнения предыдущих команд Вы не получили никаких ошибок, то можете с помощью команды df -h убедиться, что сетевой ресурс успешно примонтирован к нашему ПК на Linux. В примере WIN_HOST_IP = 192.168.1.100 и имя общей папки share
Безопасность учетных данных при монтировании через CIFS
В этом разделе опишем, как лучше всего передавать учетные данные (имя пользователя, пароль, домен) при монтировании сетевого ресурса к ОС на базе Линукс.
Создайте файл с учетными данными для cifs: /etc/cifs-credentials
Внутрь поместите следующее содержимое:
Задайте права для этого файла:
Теперь мы можем подключить общую папку такой командой:
Как сделать автоматическое монтирование общей папки Windows
В примерах выше, после того, как Вы перезагрузите свой ПК, сетевой ресурс не примонтируется. Поэтому сделаем так, чтобы шара подключалась автоматически. В Linux это делается через файл /etc/fstab. Откройте этот файл любимым редактором.
И добавьте такую строку:
Следующей командой запустим монтирование всех точек, описанных в /etc/fstab
Теперь наш удаленный сетевой ресурс будет доступен даже после перезагрузки.
Как размонтировать общую папку CIFS
Размонтирование производится таким же способом, как и обычно мы жто делаем с дисками:
Часто бывает так, что сетевой ресурс занят каким-то процессом и тогда Вы получите ошибку при попытке размонтирования, тогда запустите команду с ключем -l (—lazy)
Итак, в этой статье мы рассмотрели, как быстро примонтировать удаленную сетевую папку, которая находится на хосте с Windows, к нашему хосту на Linux с помощью CIFS. Если у Вас остались какие-либо вопросы, пожалуйста, пишите в комментариях.
Автор
Админ
Возможно Вам будет это инетересно
Как инвертировать совпадение по grep
Как посмотреть список пользователей Linux
Конфигурация файла .gitignore в Git
7 thoughts on “Как подключить общую папку (сетевой ресурс, шару) Windows к Linux”
[ 13.068117] CIFS: Attempting to mount //192.168.10.250/home
[ 13.068332] CIFS VFS: Error connecting to socket. Aborting operation.
[ 13.068339] CIFS VFS: cifs_mount failed w/return code = -2
[ 13.068431] CIFS: Attempting to mount //192.168.10.250/home/Drive/школа/English
[ 13.068556] CIFS VFS: Error connecting to socket. Aborting operation.
[ 13.068564] CIFS VFS: cifs_mount failed w/return code = -2
[ 13.069981] CIFS: Attempting to mount //192.168.10.250/Учебный_год_3В
[ 13.070234] CIFS VFS: Error connecting to socket. Aborting operation.
[ 13.070241] CIFS VFS: cifs_mount failed w/return code = -2
[ 15.184815] usb 1-1: reset high-speed USB device number 2 using ehci-pci
[ 17.861600] random: crng init done
[ 17.861607] random: 7 urandom warning(s) missed due to ratelimiting
[ 23.589870] tg3 0000:3f:00.0 enp63s0: Link is up at 100 Mbps, full duplex
[ 23.589872] tg3 0000:3f:00.0 enp63s0: Flow control is off for TX and off for RX
[ 23.589901] IPv6: ADDRCONF(NETDEV_CHANGE): enp63s0: link becomes ready
Все бы хорошо, но не успевает сетевуха поднять линк
дальше вручную «sudo mount -a» и все взлетает
[ 697.728246] CIFS: Attempting to mount //192.168.10.250/home
[ 700.739946] CIFS: Attempting to mount //192.168.10.250/Учебный_год_3В
[ 701.090973] CIFS: Attempting to mount //192.168.10.250/home/Drive/школа/English
вот вопрос, как бы заставить монтироваться после поднятия линка и получение адреса
ноут по wifi нормально отрабатывает, а системник с обычной сетевухой нет