- How to Mount a Windows Share Folder on Linux
- Share Your Windows Folder
- Install CIFS-utils
- Mount Windows SMB Share on Linux
- Sharing Files Between Linux and Windows
- Ubuntu Wiki
- MountWindowsSharesPermanently
- Prerequisites
- CIFS installation
- Mounting unprotected (guest) network folders
- Mount password protected network folders
- Special permissions
- Mount password protected shares using libpam_mount (Ubuntu 9.04)
- Troubleshooting
- Login errors
- Unprotected network folder won’t automount
- Mount during login instead of boot
- Slow shutdown due to a CIFS/Network Manager bug
- CIFS Options Deprecated
- Use of tilde in pathnames such as «credentials=
- Mount windows sharing on linux
- Установка CIFS
- Монтируем Windows Share (сетевой ресурс)
- Безопасность учетных данных при монтировании через CIFS
- Как сделать автоматическое монтирование общей папки Windows
- Как размонтировать общую папку CIFS
- Автор
- Возможно Вам будет это инетересно
- Как инвертировать совпадение по grep
- Как посмотреть список пользователей Linux
- Конфигурация файла .gitignore в Git
- 7 thoughts on “Как подключить общую папку (сетевой ресурс, шару) Windows к Linux”
How to Mount a Windows Share Folder on Linux
Linux and Windows systems have major differences, with different file systems and protocols in use. Sharing files between them can be difficult, especially because they use two different sharing protocols.
That doesn’t mean it’s impossible to mount a Windows share folder on Linux, however. Follow along below to find out how.
Share Your Windows Folder
Before you do anything, you need to ensure that Windows has been correctly set up to allow for networking file sharing.
To enable this on Windows 10, right-click on the network icon in the notifications area of your Windows taskbar. From here, click “Open Network & Internet Settings.”
Under the “Status” category, click “Sharing options.”
In your Windows sharing options menu, make sure that “Turn on network discovery” and “Turn on file and printer sharing” are enabled.
Click the radio buttons next to both options to make sure this is the case.
Click “Save changes” to save your settings. Once this is done, open Windows File Explorer and locate the folder you’re looking to share with your Linux PC.
Right-click the folder and click “Properties.”
In your folder properties, click the “Sharing” tab, then click “Advanced Sharing.” Click to enable the “Share this folder” checkbox, then click “Permissions.”
Under the “Permissions” section, set the control rights for your folder. By default, Windows will grant read-only access to your files.
If you want to allow everyone to read or write to the folder, click “Allow” for the “Full Control” permissions set. Set these permissions to suit your own requirements.
Once you’re done, click “OK” three times to close each of the dialog boxes.
Your folder should now be shared on your network, ready for you to access from your Linux PC.
Install CIFS-utils
Depending on your Linux distribution, you may be able to mount your Windows-shared folder automatically in your distribution’s file explorer.
However, this may not work correctly. The safest way to mount Windows-shared folders on Linux is to use the CIFS-utils package and mount the folder using the Linux terminal.
This allows Linux machines to access SMB file shares used by Windows PCs.
To install CIFS-utils, open a new terminal window. For Ubuntu and Debian-based distributions, type:
For Arch users, type:
Once installed, you can then mount your Windows share folder from the Linux terminal.
Mount Windows SMB Share on Linux
You’ll need to create a mount directory before you can mount your Windows SMB-shared folder on Linux. This is where Linux will mirror the contents of your shared folder.
To do that, open a terminal window and type:
Once created, type the following:
Replace “Windows” with the IP address or hostname for your Windows PC and “SharedFolder” with your shared folder name. For the username, replace “account” with your Windows username or full Microsoft account email.
You’ll be asked to provide your Windows password before the mounting process is complete. Type this in, then click Enter. If you used the correct information, your Windows folder should now be mounted and accessible in the folder you created.
Sharing Files Between Linux and Windows
Mounting Windows and Linux shared folders gives you the freedom to access your most important files, no matter the operating system. The SMB protocol is well supported on Linux, so you shouldn’t find it difficult to continue accessing your Windows files and folders once you’ve installed the CIFS-utils package.
If you’d rather use a single system, here are five of the best Linux distros for Windows users you could use.
Ben is a UK based tech writer with a passion for gadgets, gaming, and general geekiness.
Ubuntu Wiki
MountWindowsSharesPermanently
This document describes how to mount CIFS shares permanently. The shares might be hosted on a Windows computer/server, or on a Linux/UNIX server running Samba. This document also applies to SMBFS shares, which are similar to CIFS but are deprecated and should be avoided if possible (link).
(This document does not describe how to host the shares yourself, only how to access shares that are hosted somewhere else. For hosting shares, use Samba.)
Prerequisites
We’re assuming that:
- Network connections have been configured properly.
Your local (Ubuntu) username is ubuntuusername.
Share username on Windows computer is msusername.
Share password on Windows computer is mspassword.
The Windows computer’s name is servername (this can be either an IP address or an assigned name).
The name of the share is sharename.
You want to mount the share in /media/windowsshare.
CIFS installation
On older systems:
Mounting unprotected (guest) network folders
First, let’s create the mount directory. You will need a separate directory for each mount.
Then edit your /etc/fstab file (with root privileges) to add this line:
guest indicates you don’t need a password to access the share,
uid=1000 makes the Linux user specified by the id the owner of the mounted share, allowing them to rename files,
iocharset=utf8 allows access to files with names in non-English languages. This doesn’t work with shares of devices like the Buffalo Tera Station, or Windows machines that export their shares using ISO8895-15.
If there is any space in the server path, you need to replace it by \040, for example //servername/My\040Documents
After you add the entry to /etc/fstab type:
This will (re)mount all entries listed in /etc/fstab.
Mount password protected network folders
The quickest way to auto-mounting a password-protected share is to edit /etc/fstab (with root privileges), to add this line:
This is not a good idea however: /etc/fstab is readable by everyone and so is your Windows password in it. The way around this is to use a credentials file. This is a file that contains just the username and password.
Using a text editor, create a file for your remote servers logon credential:
Enter your Windows username and password in the file:
Save the file, exit the editor.
Change the permissions of the file to prevent unwanted access to your credentials:
Then edit your /etc/fstab file (with root privileges) to add this line (replacing the insecure line in the example above, if you added it):
Save the file, exit the editor.
Finally, test the fstab entry by issuing:
If there are no errors, you should test how it works after a reboot. Your remote share should mount automatically.
Special permissions
If you need special permission (like chmod etc.), you’ll need to add a uid (short for ‘user id’) or gid (for ‘group id’) parameter to the share’s mount options.
Mount password protected shares using libpam_mount (Ubuntu 9.04)
In addition to the initial assumptions, we’re assuming that
Your username and password are the same on the Ubuntu machine and on the network drive.
Edit /etc/security/pam_mount.conf.xml using your preferred text editor.
First, we’re moving the user specific config bits to a file which users can actually edit themselves: remove the commenting tags ( ) surrounding the section called . Save the file when done. With this in place, users can create their own
Add the following:
Troubleshooting
Login errors
If you get the error «mount error(13) permission denied», then the server denied your access. Here are the first things to check:
- Are you using a valid username and password? Does that account really have access to this folder?
Do you have whitespace in your credentials file? It should be password=mspassword, not password = mspassword.
Do you need a domain? For example, if you are told that your username is SALES\sally, then actually your username is sally and your domain is SALES. The fstab entry should read: . username=sally,password=pass,domain=SALES. Or: . credentials=/path/to/file,domain=SALES.
Is the security setting correct? The most common is sec=ntlm, but you can also try the other options listed at the mount.cifs man page. The man page list leaves out the option sec=lanman for some reason, but you should try that one as well (see discussion).
Unprotected network folder won’t automount
I’ve had a situation where an unprotected network folder wouldn’t automount during bootup, but after manually entering «sudo mount -a» was mounted correctly. I solved this by replacing the «guest» option by «username=guest,password=». If anyone has an explanation for this, please leave a comment.
Mount during login instead of boot
If for some reason/etc/rc0.d/S31umountnfs.sh (networking problems for example) the automatic mounting during boot doesn’t work, you can add the «noauto» parameter to your smbfs fstab entry and then have the share mounted at login.
Slow shutdown due to a CIFS/Network Manager bug
If you use Network Manager, and are getting really slow shutdowns, it’s probably because NM shuts down before unmounting the network shares. That will cause CIFS to hang and wait for 60 seconds or so. Here’s how to fix it:/etc/rc0.d/S31umountnfs.sh
Ubuntu 12.04 already runs umountnfs.sh at reboot and shutdown by default (/etc/rc0.d/S31umountnfs.sh and /etc/rc6.d/S31umountnfs.sh) so this is no longer necessary.
CIFS Options Deprecated
Using dmask or fmask in the fstab file produces the following warnings: WARNING: CIFS mount option ‘dmask’ is deprecated. Use ‘dir_mode’ instead. WARNING: CIFS mount option ‘fmask’ is deprecated. Use ‘file_mode’ instead.
Instead use this format: file_mode=0777,dir_mode=0777 . Or in some cases you might need to use file_mode=0777,dir_mode=0777,nounix (see discussion)
Use of tilde in pathnames such as «credentials=
Curiously, using credentials=
/.smbcredentials in fstab didn’t work. I had to use the full path, i.e. /home/username/.smbcredentials
(This is likely because the tilde «
» is only a shell short-hand alias for «$HOME»; it isn’t something recognized system-wide by all programs, especially not in a system file table where the concept of «HOME» doesn’t really exist. -Ian!)
MountWindowsSharesPermanently (последним исправлял пользователь shippj 2020-07-22 01:52:19)
The material on this wiki is available under a free license, see Copyright / License for details.
Mount windows sharing on linux
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 нормально отрабатывает, а системник с обычной сетевухой нет