Mount windows sharing on linux

Содержание
  1. Как в Linux монтировать шару CIFS
  2. Подготовка
  3. Установка пакетов
  4. Сетевые порты
  5. Синтаксис
  6. Ручное монтирование
  7. Автоматическое монтирование CIFS через fstab
  8. Примеры использования опций
  9. Версии SMB
  10. Монтирование от гостевой учетной записи
  11. Права на примонтированные каталоги
  12. Как монтировать общие папки Windows в системах Linux
  13. How to Mount Windows Share on Linux using CIFS
  14. В этом руководстве мы расскажем, как вручную и автоматически монтировать общие папки Windows в системах Linux.
  15. Установка пакетов утилит CIFS
  16. Монтирование CIFS Windows Share
  17. Авто монтаж
  18. Размонтирование Windows Share
  19. Вывод
  20. How to Mount Windows Share on Ubuntu Linux
  21. Installing CIFS
  22. Mounting a Windows Share
  23. Secure CIFS credential
  24. Auto mount the shares
  25. Unmount the shares
  26. Conclusion
  27. More Articles You May Like
  28. 6 Comments. add one
  29. How to Mount a Windows Share Folder on Linux
  30. Share Your Windows Folder
  31. Install CIFS-utils
  32. Mount Windows SMB Share on Linux
  33. Sharing Files Between Linux and Windows in Dual Boot
  34. Frequently Asked Questions
  35. 1. Why do I get a syntax error when trying to mount a folder in Linux?
  36. 2. Can I mount a shared folder if I use VirtualBox?
  37. 3. Can I mount guest, network, or password protected folders?
  38. 4. Why do I only have read access for the shared folder?
  39. 5. Why aren’t folder changes showing up?
  40. Wrapping Up
  41. One comment
  42. Leave a Comment Cancel reply
  43. Popular Posts

Как в Linux монтировать шару CIFS

Что такое Linux и CIFS простыми словами.

Работа с общими папками Windows происходит с использованием протокола CIFS (SMB). Все примеры в данном руководстве выполняются на Linux Ubuntu и CentOS.

Подготовка

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

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

yum install cifs-utils

apt-get install cifs-utils

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

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

Синтаксис

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

mount.cifs //192.168.1.1/public /mnt

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

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

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

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

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

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

username=dmosk
password=dPassw0rd
domain=dmosk.local

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

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

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

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

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

//192.168.1.10/share /mnt cifs guest 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 .

Источник

Как монтировать общие папки Windows в системах Linux

How to Mount Windows Share on Linux using CIFS

В этом руководстве мы расскажем, как вручную и автоматически монтировать общие папки Windows в системах Linux.

В операционных системах Linux и UNIX общий ресурс Windows можно смонтировать в определенной точке монтирования в дереве локальных каталогов, используя cifs параметр mount команды.

Общая файловая система Интернета (CIFS) — это сетевой протокол обмена файлами. CIFS является формой SMB.

Установка пакетов утилит CIFS

Чтобы смонтировать общий ресурс Windows в системе Linux, сначала необходимо установить пакет утилит CIFS.

Установка утилит CIFS в Ubuntu и Debian:

Установка утилит CIFS в CentOS и Fedora:

Имя пакета может отличаться в разных дистрибутивах Linux.

Монтирование CIFS Windows Share

Монтирование удаленного общего ресурса Windows аналогично монтированию обычных файловых систем.

Сначала создайте каталог, который будет служить точкой монтирования для удаленного общего ресурса Windows:

Запустите следующую команду как пользователь root или пользователь с правами sudo для монтирования общего ресурса:

Вам будет предложено ввести пароль:

В случае успеха не выводится.

Чтобы убедиться, что удаленный общий ресурс Windows успешно смонтирован, используйте команду mount или df -h .

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

Читайте также:  Kali linux discover не удалось получить список приложений

Пароль также можно указать в командной строке:

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

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

Файл учетных данных имеет следующий формат:

Файл не должен быть доступен для чтения пользователям. Чтобы установить правильные разрешения и владельца , запустите:

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

По умолчанию подключенный общий ресурс принадлежит пользователю root, а разрешения установлены на 777.

Используйте dir_mode опцию, чтобы установить разрешение каталога и file_mode установить разрешение файла:

Пользователь по умолчанию и группа собственность могут быть изменены с uid и gid опциями:

Чтобы установить дополнительные параметры , добавьте их в виде списка через запятую после -o параметра. Чтобы получить список всех опций монтирования, введите man mount ваш терминал.

Авто монтаж

Когда общий ресурс монтируется вручную с помощью mount команды, он не сохраняется после перезагрузки.

/etc/fstab Файл содержит список записей , которые определяют , где , как и то , что файловая система будет смонтирована на старте системы.

Чтобы автоматически смонтировать общий ресурс Windows при запуске вашей системы Linux, определите монтирование в /etc/fstab файле. Строка должна содержать имя хоста или IP-адрес ПК с Windows, имя общего ресурса и точку монтирования на локальном компьютере.

Откройте /etc/fstab файл в текстовом редакторе :

Добавьте следующую строку в файл:

Выполните следующую команду для монтирования общего ресурса:

mount Команда, будет читать содержание /etc/fstab и установить долю.

При следующей перезагрузке системы общий ресурс Windows будет смонтирован автоматически.

Размонтирование Windows Share

Команда umount отсоединяет (размонтирует) смонтированную файловую систему от дерева каталогов.

Чтобы отсоединить подключенный общий ресурс Windows, используйте umount команду с указанием либо каталога, в котором он был подключен, либо удаленного общего ресурса:

Если в fstab файле CIFS есть запись в файле, удалите ее.

Команда umount не сможет отсоединить общий ресурс, когда он используется. Чтобы узнать, какие процессы обращаются к общему ресурсу Windows, используйте fuser команду:

Найдя процессы, вы можете остановить их с помощью kill команды и размонтировать общий ресурс.

Если у вас по-прежнему возникают проблемы с размонтированием общего ресурса, используйте параметр -l ( —lazy ), который позволяет размонтировать занятую файловую систему, как только она больше не будет занята.

Вывод

В Linux вы можете смонтировать общий доступ к Windows, используя mount команду с cifs параметром.

Источник

How to Mount Windows Share on Ubuntu Linux

CIFS (Common Internet File System) is a popular file sharing protocol on Internet. It allows users on a Linux system access to a particular mount point on a windows share.

CIFS is an implementation of SMB (Server Message Block) — a protocol used for network file sharing.

This tutorial will go through all steps of installing and configuring relevant utilities in order to mount windows share on Linux system.

Installing CIFS

Install cifs-utils package on Ubuntu Linux by using the following command line

Mounting a Windows Share

In this section, the tutorial will show you the way to manually and automatically mount windows share on Linux systems.

Creating a directory on your Ubuntu Linux machine, the name of directory is arbitrary. In the below command line, I created a folder named winshare under /mnt

/mnt/winshare is the mount point of the remote windows share.

Windows share can be mounted on your Ubuntu Linux system mount point using cifs option of mount command

WIN_SHARE_IP is the IP address of windows machine.

If the $windows_user is in a windows domain, specify the domain as the following command line

By default, linux mount windows share with the full permission (rwx or 777). If you want to change the permission on your own, please use the dir_mode and file_mode options to set permission for directory and file.

You also can change the default ownership of user and group by specify the uid (user id) and gid (group id) options.

Once the windows share is successfully mounted, using command df -h for verifying the mounting windows share in Linux. In the following example, WIN_SHARE_IP = 192.168.1.8 and $shared_name = sharefolder

Secure CIFS credential

This section will explain how to use a credential file when your Ubuntu Linux mount the share using command.

Create a cifs credentials file: /etc/cifs-credentials. The file contains the below information:

Grant permission read and write to credentials file:

Now, we can mount the share using credentials with command as follows:

Auto mount the shares

If you manually mount the shares using mount command, when you reboot your Linux machine, the shares will be lost.

The file /etc/fstab contains the necessary configuration that allows automatically mount cifs permanently.

Edit the /etc/fstab file with your favorite editors (vim, nano. )

Then add the following line to the file.

Run the command to mount all the entries listed in /etc/fstab

Читайте также:  Не найдены драйвера оптического привода при установке windows

Since then, the mount cifs will be persistent across reboots.

Unmount the shares

In order to unmount a share, you have to determine the mount point. In the above example, mount point is /mnt/winshare. Use the umount command:

If the mount point is in a busy process and the above command failed, run command with option -l (—lazy)

Conclusion

The tutorial has gone through all steps to mount a windows share on Ubuntu Linux using CIFS. If you have any questions, feel free to reach out to us.

6 Comments. add one

I do not understand why you need to specify the Windows machine IP adress. These are constantly changing when using DHCP, which almost everyone uses. Does that mean that one has to go through the above procedure every day if one wants to connect to a Windows machine whose IP address has changed (people shut off their computers at night, likely getting a new IP address asigned the next day when turned on)? Is there a way that automatically detects the target Windows machine, as Windows does in its own networking system?

If IP address changes, use DNS names

This doesn’t appear to work in the latest ubuntu release.
If I do it from the command line, it requires the «vers=2.0» option.
Not sure how to fix it in the fstab. All I get is error(22) invalid argument.

What does tail -f /var/log/kern.log shows when you mount?

I’m not sure if it’s the cause of your error, but there’s a typo in the fstab line — where it says «dir_node=0755», it should say «dir_mode=0755». Double check that’s correct in your fstab.

Источник

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.

Also read: How to View Shared Files and Folders in Windows 10

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, 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.

Читайте также:  Windows server 2012 домен политика паролей

Sharing Files Between Linux and Windows in Dual Boot

Sharing files between Windows and Linux works great when you mount a shared folder between the two devices, but can you still share files with a dual boot setup? Linux and Windows have separate file systems. Linux usually uses Ext4, while Windows uses NTFS and also works with FAT32. This doesn’t mean it’s impossible to see and share files, though.

You’ll need a compatible Windows system, build 20211 or higher, and a few other resources to make it work. Don’t worry. Everything is free. This guide walks you through each step in the process, including a way to read and share files between Windows and Linux.

Frequently Asked Questions

1. Why do I get a syntax error when trying to mount a folder in Linux?

Either there’s a small error in the command in the terminal window, or you have a space in the folder name. Spaces don’t always come across correctly in the syntax. Instead of recognizing the command as the full name of the folder, the system sees two unrelated items.

Avoid this by placing the name in quotes. For instance, Shared Folder would become “Shared Folder.” Of course, you can also just rename the Windows 10 folder to place the words together or have a dash between them.

2. Can I mount a shared folder if I use VirtualBox?

Yes. The process should work the same way. You can also share devices, such as USB drives.

3. Can I mount guest, network, or password protected folders?

Yes, but since you’re not using the main Windows 10 account, you will need to adjust the syntax a bit. Plus, if you’re mounting a network folder, you’ll also need the server or machine name.

While this guide applies to Ubuntu, it should work for most major Linux distros as well. It lists the syntax for different scenarios, assuming you’ve already completed all of the steps (except the final mounting) above.

4. Why do I only have read access for the shared folder?

If you want to store files in the shared folder from Linux, make sure you have full read/write access to the folder in Windows. If the Windows user account only has read permission, this is the only permission you’ll have from Linux as well. You must change your account permissions from within Windows 10. For companies, you’ll need your IT admin to make the change for you.

5. Why aren’t folder changes showing up?

If you’ve made changes to the permissions of the folder, they may not show up immediately in Linux. You’ll need to remount the folder for changes to take effect.

Use the command above to remount any shared folders. This should ensure things work as expected. If you have any random glitches, remounting typically fixes them.

Wrapping Up

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.

Crystal Crowder has spent over 15 years working in the tech industry, first as an IT technician and then as a writer. She works to help teach others how to get the most from their devices, systems, and apps. She stays on top of the latest trends and is always finding solutions to common tech problems.

One comment

I make an NTFS partition and save files to be shared on it. Linux files have ‘permissions’ which are not saved on an NTFS partition, so they become available to anyone, even a Windows pain!

Leave a Comment Cancel reply

RedMagic 6S Pro Review: Gaming Is Serious Business.

How to Boot to Recovery Mode (Safe Mode) in Ubuntu

Ubuntu Software Center Not Working? Here Are the Fixes

How to Stress Test a Graphics Card on Linux

How to Mount Your iPhone as an External Drive in Ubuntu

How to Fix Ubuntu Freezing in VirtualBox

How to Fix «Repository Does Not Have Release File» Error

How to Combine PDF Files on Windows and Linux

How to Reset the Root Password in Linux

8 Reasons to Switch from Windows to Linux

5 of the Best Linux Distros for Developers and Programmers

Affiliate Disclosure: Make Tech Easier may earn commission on products purchased through our links, which supports the work we do for our readers.

Источник

Оцените статью