Linux mount network share

Как в 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.

Читайте также:  Лучшие терминалы linux для андроид

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Если пользователь находится в рабочей группе или домене 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 NFS Share In Linux and Windows?

Network File System or NFS is a network-based filesystem protocol which is mainly used to share files and folders over the network. NFS is a UNIX based technology but can be used by most of the operating systems like Linux, Ubuntu, Debian, Kali, Mint, Fedora, CentOS, RedHat and Windows operating systems Windows 7, Windows 8, Windows 10, Windows Server 2008, Windows Server 2012, Windows Server 2016.

Читайте также:  Apple audio device для windows 10

Install NFS Server

NFS packages mainly divided into two parts. First is the server side packages which will install related kernel modules and server tools.

Ubuntu, Debian, Mint, Kali Client Packages

Fedora, CentOS, Fedora Client Packages

Ubuntu, Debian, Mint, Kali Server Packages

After the installation is complete the nfs-server service will be also created automatically.

Fedora, CentOS, Fedora Server Packages

Check NFS Service Status

As the NFS shares will be served over nfs-server we need to the if it is working. We will use systemctl status command with the nfs-server service name.

Check NfS Service Status

We can see that the service is active and working properly.

Start NFS Service

If the service is not started or stopped in any way we need to start the nfs-server service. We will use systemctl start command with the nfs-server service name like below.

Create NFS Share

NFS main configuration is stored in the /etc/exports file. Each share is created line by line. For example, if we want to share /mnt with the IP address 192.168.10.10 we will use the following configuration.

But generally, we share the files and folders with everyone who has access to the NFS server. We can use the following configuration to share everyone.

Enable Exports

After creating the share configuration we need to refresh the NFS table where the shares are stored. We can simply use exportfs command with the -a option which will add current configuration to the NFS table.

Mount NFS Share For Linux

We can use mount command in order to mount NFS share. We will specify the filesystem type as nfs to the mount command with the -t option like below. The server IP address is 192.168.142.144 and share is /mnt . We will mount to the /home/ismail/poftut1 .

List NFS Mounts

After mounting the NFS share we can check it by listing the NFS mount. We will use mount command and filter NFS shares with the grep command like below.

List NFS Mounts

Unmount NFS Share For Linux

We can unmount already mounted NFS shares with the umount command. We will just specify the mount path to the umount command with the sudo command like below.

Mount NFS Share For Windows

First, we will enable NFS modules or features on Windows operating systems. Open Start > Control Panel > Programs. Select Turn Windows Features on or off. Select Services for NFS. Click OK.

We can mount NFS shares in Windows operating systems too. We will use mount command. We will also provide nolock option and other parameters like remote NFS server IP address and local drive which is Z in this case.

Alternatively, we can use net use command which can also mount NFS shares. We will provide the partition name which is z and remote NFS server.

Источник

Mounting and mapping shares between Windows and Linux with Samba

More Linux resources

In my previous article, Interoperability: Getting started with Samba, I covered installing and configuring Samba shares on a Linux server. The real power of Samba comes when Windows clients can communicate with Linux file servers. In this article, I will cover how you can access Samba shares from both Linux and Windows clients.

Install the Samba client packages

To access Samba share from Linux clients we need to install a few Samba client packages.

On the client machine, install the samba-common and samba-client packages.

Check for available shares

Let’s check if we can access our shares from the server. We can use either the hostname or ip address of the server. If you use the hostname , make sure DNS is working.

Читайте также:  Как использовать timeshift linux

Create a directory that we can use as our mount point. I’m going to create a directory under /mnt , but you can use any directory you would like to. You may need to configure SELinux on that directory.

Now, mount the share.

Now that we’ve mounted our share, we can check the mounts with the following command:

Let’s make that directory mount persistently so it can withstand a reboot. Using the text editor of your choice, edit the /etc/fstab file. You can do this in multiple ways, but I’m going to demonstrate two ways to mount the Samba share at boot in /etc/fstab .

The first option provides a username and password for the Samba user in the fstab .

The other option is to create a credential file. You can call this file anything, but I would like to call it cred . I would like to place credentials files in the home directory of the user. In our demonstration it will be /home/user/.cred .

The _netdev option is important since we are mounting a network device. Clients may hang during the boot process if the system encounters any difficulties with the network.

Now create that .cred file inside the user’s home directory.

Next, add the Samba user’s username and password.

Finally, mount all filesystems.

Access a share from a Windows client

I will be using Windows 10 as my client machine with a workgroup called SAMBA . We need to create a local user account on the Windows machine that matches the username and password of the Samba user account we created in my previous article. Although account creation is not necessary, this will make things simpler when accessing the share.

Like I mentioned above, this step is optional and you can skip it completely. Although there are multiple approaches to adding a new local user on a Windows machine, for the simplicity of this article I will be using PowerShell. Launch PowerShell as an administrator and issue following commands:

Now that we have created a new local user account matching the Samba user account, we can log in to Windows with our newly created user account.

Access a share from Windows Explorer

To access the Samba share from Windows Explorer, start typing the IP address to our share in the search area. I am using the hostname of the Samba server. In my case, it is centos . You can also access the share by using the IP address of the Samba server.

You might be prompted to enter the username and password to access the share if you skipped the local user creation process. If you get prompted for credentials, enter the Samba username and password we created in the previous article.

You will need to enter the Samba share path every time you want to access the share. There is a better way to access the share by mapping a drive to Samba share in Windows.

Mapping a drive to a Samba share

To map a drive to the Samba share, open PowerShell and issue following command:

Accessing a Samba share on Linux and Windows is easy. With this basic setup, you will be able to access file shares from client machines in your network. With somewhat more configuration, you can deploy Samba shares in a domain environment. Samba can do more than file share. If you would like to learn more about Samba, read this article about Windows and Linux interoperability. This is a basic set up, but you can do so much more with Samba.

[ Want to test your sysadmin skills? Take a skills assessment today. ]

Источник

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