Mount windows share to ubuntu

Обновлено:
Опубликовано:

Используемые термины: 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/dPassw0rddomain указывать не обязательно, если аутентификация выполняется без него.

Задаем права на созданный файл, чтобы доступ был только у пользователя, скажем, 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. Пример скрипта для создания резервной копии файлового сервера.

Needs Updating
This article needs updating to include the latest versions of Ubuntu. More info…

Please see https://launchpad.net/bugs/1244123 about one reason for the update need.


MountSAMBAshareFSTAB

Contents

  1. Introduction

    1. Two methods, depending on share host
  2. Prerequisites
  3. Setup

    1. Single User
    2. Multiple Users
    3. Credentials File
    4. Editing fstab
    5. Ensure
    6. Completing Setup
  4. Troubleshooting

    1. cifs will not mount
    2. Server is down, filesystem is hung
    3. CIFS remote ownership enforcement
    4. System Hangs on Shutdown
    5. Login without Credentials
    6. 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)

If you need to access Windows shared folders from Ubuntu, it can be done easily by installing and configuring Samba. Samba is a software suite that provides file and print services for Windows clients, and it allows Linux and Windows machines to share files and printers. By using Samba, you can create Linux shares that can be accessed by Windows clients, as well as access Windows shares from Linux machines.

In this guide, we will walk you through the process of accessing Windows shared folders from Ubuntu using Samba. We will cover the following steps:

  1. Install Samba on Ubuntu
  2. Configure Samba on Ubuntu
  3. Access Windows shared folder from Ubuntu

By following these steps, you will be able to access Windows shared folders from Ubuntu and easily transfer files between the two operating systems.

Step 1: Update Ubuntu

Before installing Samba, it’s always a good idea to update Ubuntu to ensure that you have the latest software and security patches. You can do this by opening a terminal and running the following commands:

sudo apt-get update
sudo apt-get upgrade

Step 2: Install Samba

Before you can mount a Windows shared folder on Ubuntu, you need to make sure that Samba is installed on Ubuntu. If you have not already installed Samba, you can do so by running the following command in the terminal:

sudo apt-get install samba

Step 3: Find the IP address of the Windows machine

Before you can mount the Windows shared folder on Ubuntu, you need to know the IP address of the Windows machine. You can find this by opening a Command Prompt on the Windows machine and running the command:

ipconfig

Look for the IPv4 address, which should look something like “192.168.1.10”. Note down this IP address.

Step 4: Create a mount point

Before you can mount the Windows shared folder on Ubuntu, you need to create a mount point on Ubuntu. This is the folder where the Windows shared folder will be mounted. You can create a mount point by running the following command in the terminal:

sudo mkdir /mnt/windows

This will create a folder called “windows” in the “/mnt” directory.

Step 5: Mount the Windows shared folder

To mount the Windows shared folder on Ubuntu, you need to run the following command in the terminal:

sudo mount -t cifs //windows_ip/shared_folder /mnt/windows -o username=windows_username,password=windows_password

Replace “windows_ip” with the IP address of the Windows machine that you noted down earlier, “shared_folder” with the name of the shared folder on the Windows machine, “windows_username” with your Windows username, and “windows_password” with your Windows password.

Step 6: Verify the mount

Once you have mounted the Windows shared folder on Ubuntu, you can verify the mount by running the following command in the terminal:

ls /mnt/windows

This should display the contents of the Windows shared folder.

Step 7: Automate the mount

If you want the Windows shared folder to be automatically mounted every time you start Ubuntu, you can add the mount command to the “/etc/fstab” file. To do this, open the “/etc/fstab” file in a text editor using the following command:

sudo nano /etc/fstab

Add the following line to the end of the file:

//windows_ip/shared_folder /mnt/windows cifs username=windows_username,password=windows_password 0 0

Save the file and exit the text editor.

Now, every time you start Ubuntu, the Windows shared folder will be automatically mounted to the “/mnt/windows” directory.

By following these steps, you can easily mount a Windows shared folder on Ubuntu using Samba, and access files on the Windows machine from Ubuntu.

You may visit websites homepage for coding related article.

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 .

This post shows students and new users steps to mount Windows shares on Ubuntu Linux. For this tutorial, I’ll be using Windows 11 and Ubuntu Linux.

A Windows share can be mounted on a particular mount point on Ubuntu Linux using the cifs option when using the mount command. One can use the mount command to mount shares at a particular mount point identified on a Linux directory.

When mounting a Windows share, the Common Internet File System (CIFS) network file-sharing protocol is suitable. It’s part of the SMB protocol that allows File and printer sharing on Windows systems.

Below, we’ll show you how to configure a Windows 11 machine to allow file sharing to allow Ubuntu to mount Windows shares.

To start mounting Windows shares on Ubuntu Linux, follow the steps below.

Enable Network Discovery in Windows 11

As mentioned above, shares must be advertised for other devices to view or access. In Windows, Network Discovery needs to be turned on to advertise shares to be viewed from other devices.

If your Windows devices cannot see or discover each other on your private Network, it might likely be that Network Discovery is disabled.

To enable Network Discovery, continue below.

Windows 11 has a centralized location for the majority of its settings. Everything can be done, from system configurations to creating new users and updating Windows from its System Settings pane.

To get to System Settings, you can use the Windows key + I shortcut or click on Start ==> Settings, as shown in the image below:

Alternatively, you can use the search box on the taskbar and search for Settings. Then select to open it.

Windows Settings pane should look similar to the image below. In Windows Settings, click Network & Internet, then select Ethernet on the right pane of your screen shown in the image below.

In the Ethernet settings pane, under Network profile type, choose Private. This profile will allow devices in your Network to be discovered. This profile should also be selected if you need file sharing or use apps that communicate over this Network.

The private profile is suitable for homes, workplaces, and trusted networks.

If you have other networks like Wi-Fi (if you’re connected to a wireless network) or Ethernet (if you’re connected to a network using a network cable), you can also set the profile type to Private.

When you’re done, exit and network discovery should be enabled.

Turn on Public Folder Sharing in Windows 11

Use the steps below to set up file sharing.

Windows 11 has a centralized location for the majority of its settings. Everything can be done, from system configurations to creating new users and updating Windows from its System Settings pane.

However, changing the account username is still done in the old Control Panel. To get to Control Panel, you can click on Start and start typing Control Panel as shown in the image below:

In the Control Panel, select Network and Internet, as highlighted in the image below.

Select Network and Sharing Center on the next page, as highlighted below.

Next, select Change advanced sharing settings as highlighted below.

Select Private (current profile) and Turn on File and printer sharing in the Advanced sharing center.

Save your changes and exit.

On the same Advance sharing options page, scroll down All networks.

You should see settings for Public folder sharing, Media streaming, File sharing connections, and Password protected sharing. Windows should automatically turn on File and printer sharing in private networks. However, in some instances, this will not be enabled.

If you can not automatically find printers and shared resources in your private Network, then the File sharing option may be disabled.

Only people with accounts on the local computer or in the domain environment can access shared files and printers if you enable password-protected sharing.

Make your changes and save, then exit.

The settings above can easily be done using the commands below as administrator.

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=Yes
netsh advfirewall firewall set rule group="Network Discovery" new enable=Yes

It would be best to open the command prompt as administrator to run the above commands.

How to create Windows shares

You cannot mount a Windows share if you don’t share a folder or directory. Read the post below to learn how to create a share on Windows.

You must complete the steps in the post below to create a share before mounting it on Ubuntu Linux.

How to create Windows 11 shares

Now that you have created a share on Windows continue below to mount it on Ubuntu Linux.

How to mount Windows shares on Ubuntu Linux

Now that Network Discovery and file sharing are enabled, you can log onto Ubuntu Linux and begin mounting Windows shares.

You must first install the CIFS utility package to mount a Windows share on Ubuntu Linux. The commands below will install it.

sudo apt update
sudo apt install cifs-utils

After running the commands above, you can begin mounting shares using the mount commands with the cifs file system. Mounting a remote Windows share is similar to mounting regular file systems.

A simple mount command below will mount a Windows share to the /mnt/Windows_Share directory on Ubuntu Linux. Make sure that the directory or folder already exists on Ubuntu Linux.

sudo mount -t cifs -o username=<Windows_UserName> //WindowsPC_IP/<ShareName> /mnt/Windows_Share

The commands above are detailed below:

  • mount -t cifs = file system type (protocol)
  • username = username of Windows account
  • //WindowsPC_IP/ShareName = the Windows PC share name
  • /mnt/Windows_Share = the mount point on Ubuntu

For example, if my Window username is richard, I’d run the commands below:

sudo mount -t cifs -o username=richard //10.0.2.18/Ubuntu /mnt/windows

When you run the commands above, it should prompt you for your Windows account password to mount the share.

Once the share is mounted, the mount point becomes the root directory of the mounted file system. You can work with the remote files as if they were local files.

If you want to include the Password with the mount command, simply add the Password filed option as below:

sudo mount -t cifs -o username=<Windows_UserName>,password=<Windows_Password> //WindowsPC_IP/<ShareName> /mnt/Windows_Share

The root owns the mounted share by default, and the permissions are set to 777. If you want to set custom permissions, you can use dir_mode option to set the directory permission and file_mode to set the file permission.

An example format would be:

sudo mount -t cifs -o dir_mode=0755,file_mode=0755 //WidnowsPC_IP/<ShareName> /mnt/Windows_Share

For security reasons, using a file for account credentials is recommended so it’s not exposed to the mount commands.

You can create a file, type in the username, Password, and domain details, and then reference the File with the mount command.

The format of the credentials should be entered as below:

username=user
password=password
domain=domain

Then protect the File using the commands below if the File is located at /etc/credentials.

sudo chown root: /etc/credentials
sudo chmod 600 /etc/credentials

You can then use the mount commands below with options for credentials as shown:

sudo mount -t cifs -o credentials=/etc/credentials //WindowsPC_IP/<ShareName> /mnt/Windows_Share

How to auto-mount Windows shares on Ubuntu

If you don’t always want to type the mount commands to mount Windows shares, you can utilize the/etc/fstab file to mount the shares automatically.

The File contains a list of entries that define where and how the filesystem will be mounted on system startup.

Run the commands below to open the File:

sudo nano /etc/fstab

Then enter the mount commands at the bottom of the File and save.

//WindowsPC_IP/ShareName  /mnt/Widows_Share  cifs  credentials=/etc/credentials,file_mode=0755,dir_mode=0755 0   0

Now every time Ubuntu Linux starts up, the share should automatically.

If you want to unmount, run the commands below to disconnect the mounted share.

sudo umount /mnt/win_share

That should do it!

Conclusion:

  • Successfully mounting Windows shares on Ubuntu Linux requires enabling network discovery and file sharing on Windows 11.
  • The CIFS utility package is essential for mounting shares; ensure it is installed on your Ubuntu system.
  • Use appropriate mount commands, including specifying the correct username and share details.
  • For security and convenience, consider using a credentials file to manage your Windows login details.
  • Automating the mount process through the /etc/fstab file can save time and streamline access to shared resources.
  • Following these steps allows for seamless file sharing between Windows and Ubuntu systems, enhancing productivity in a mixed-environment setup.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Skachat windows 7 бесплатно 64 bit с драйверами na fleshku
  • Windows black screen with cursor
  • Дополнения для проводника windows
  • Как убрать windows boot manager при загрузке
  • Драйвер geforce game ready сбой установки windows 11