Windows share folder for linux

В этой статье мы рассмотрим, как в Linux смонтировать общую сетевую папку, расположенную на хосте Windows. В Windows для доступа к общим сетевым папкам используется протокол SMB (Server Message Block), который ранее назывался CIFS (Сommon Internet File System). В Linux для доступа к сетевым папкам Windows по протоколу SMB можно использовать клиент cifs-utils или Samba.

    Содержание:

  • Смонтировать сетевую папку в Linux с помощью cifs-util
  • Автоматическое монтирование сетевой папки в Linux
  • Linux: подключиться к сетевой папке с помощью клиента samba

Совет. Для доступа к сетевым папкам по SMB/CIFS используется порт TCP/445. Для разрешения имени используются порты UDP 137, 138 и TCP 139. Если эти порты закрыты, вы сможете подключиться к сетевой папке Windows только по IP адресу.

Смонтировать сетевую папку в Linux с помощью cifs-util

Вы можете смонтировать сетевую папку, находящуюся на Windows хосте, с помощью утилит из пакета cifs-util. Для установки пакета выполните команду:

  • В Ubuntu/Debian: $ sudo apt-get install cifs-utils
  • В CentOS/Oracle/RHEL: $ sudo dnf install cifs-utils

Создайте точку монтирования:

$ sudo mkdir /mnt/share

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

$ sudo mount.cifs //192.168.31.33/backup /mnt/share -o user=User03

Укажите пароль пользователя Windows для подключения к сетевой папке.

mount.cifs подключить сетевую папку smb в linux

При подключении сетевой SMB папки можно задать дополнительные параметры:

$ sudo mount -t cifs -o username=User03,password=PasswOrd1,uid=1000,iocharset=utf8 //192.168.31.33/backup /mnt/share

  • //192.168.31.33/backup – сетевая папка Windows
  • /mnt/share – точка монтирования
  • -t cifs – указать файловую систему для монтирования
  • -o опции монтирования (эту опцию можно использовать только с правами root, поэтому в команде используется sudo)
  • username=User03,password=PasswOrd1 – имя и пароль пользователя Windows, у которого есть права доступа к сетевой папке. Можно указать имя пользователя guest, если разрешен анонимный доступ к сетевой папке
  • iocharset=utf8 – включить поддержку кодировки UTF8 для отображения имен файлов
  • uid=1000 – использовать этого пользователя Linux в качестве владельца файлов в папке

команда mount cifs в linux

По умолчанию шары Windows монтируются в Linux с полными правами (0755). Если вы хотите изменить права по-умолчанию при монтировании, добавьте в команду опции:

dir_mode=0755,file_mode=0755

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

IP_АДРЕС    ИМЯ_КОМПЬЮТЕРА

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

Например:

$ mcedit ~/.windowscredentials

Добавьте в файл:

username=User03
password=PasswOrd1

Для подключения к папке под анонимным пользователем:

username=guest
password=

Если нужно указать учетную запись пользователя из определенного домена Active Directory, добавьте в файл третью строку:

domain = vmblog.ru

Измените права на файл:

$ chmod 600 ~/.windowscredentials

Теперь при подключении сетевой папки вместо явного указания имени пользователя и пароля можно указать путь к файлу:

$ sudo mount -t cifs -o credentials=/home/sysops/.windowscredentials,uid=1000,iocharset=utf8 //192.168.31.33/backup /mnt/share

Отмонтировать сетевую SMB папку:

$ sudo umount /mnt/share

Автоматическое монтирование сетевой папки в Linux

Можно настроить автоматическое монтирование сетевой папки Windows через /etc/fstab.

$ sudo mcedit /etc/fstab

Добавьте в файл следующую строку подключения SMB каталога:

//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev 0 0
  • rw – смонтировать SBM папку на чтение и запись
  • nofail – продолжить загрузку ОС если не удается смонтировать файловую систему
  • _netdev – указывает что подключается файловая система по сети. Linux не будет монтировать такие файловые системы пока на хосте не будет инициализирована сеть.

Вы можете указать версию протокола SMB, которую нужно использовать для подключения (версия SMB 1.0 считается небезопасной и отключена по-умолчанию в современных версиях Windows). Добавьте в конец строки с настройками подключения параметр vers=3.0.

//192.168.31.33/backup /mnt/share cifs user,rw,credentials=/home/sysops/.windowscredentials,iocharset=utf8,nofail,_netdev,vers=3.0 0 0

Если на стороне хоста Windows используется несовместимая (старая версия) SMB, при подключении появится ошибка:

mount error(112): Host is downилиmount error(95): Operation not supported

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

$ mount -a

Linux: подключиться к сетевой папке с помощью клиента samba

Установите в Linux клиент samba:

  • В Ubuntu/Debian: $ sudo apt-get install smbclient
  • В CentOS/Oracle/RHEL: # dnf install smbclient

Для вывода всех SMB ресурсов в локальной сети:

$ smbtree -N

Вывести список доступных SMB папок на удаленном хосте Windows:

smbclient -L //192.168.31.33 -N

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

session setup failed: NT_STATUS_ACCESS_DENIED

В этом случае нужно указать учетную запись пользователя Windows, которую нужно использовать для подключения:

smbclient -L //192.168.31.33 -U User03

Если нужно использовать учетную запись пользователя домена, добавьте опцию –W:

smbclient -L //192.168.31.33 -U User03 –W Domain

smbclient вывести список общих папок на компьютере windows

Для интерактивного подключения к сетевой папке Windows используется команда:

smbclient //192.168.31.33/backup -U User03 -W Domain

или

smbclient //192.168.31.33/backup -U User03

Для анонимного доступа:

smbclient //192.168.31.33/backup -U Everyone

После успешного входа появится приглашение:

smb: \>

Вывести список файлов в сетевой папке:

dir

smbclient вывести список файлов в сетевой папке linux

Скачать файл из сетевой папки Windows:

get remotefile.txt /home/sysops/localfile.txt

Сохранить локальный файл из Linux в SMB каталог:

put /home/sysops/localfile.txt  remotefile.txt

Можно последовательно выполнить несколько команд smbclient:

$ smbclient //192.168.31.33/backup -U User03 -c "cd MyFolder; get arcive.zip /mnt/backup/archive.zip"

Полный список команд в smbclient можно вывести с помощью команды help. Команды smbclient схожи с командами ftp клиента.

При использовании команды smbclient может появиться ошибка:

Unable to initialize messaging contextsmbclient: Can't load /etc/samba/smb.conf - run testparm to debug it.

Чтобы исправить ошибку, создайте файл /etc/samba/smb.conf.

Если на хосте Windows отключен протокол SMB 1.0, то при подключении с помощью smbclient появится ошибка:

Reconnecting with SMB1 for workgroup listing.
protocol negotiation failed: NT_STATUS_CONNECTION_RESET
Unable to connect with SMB1 -- no workgroup available.

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 .

If you work with different operating systems, it’s handy to be able to share files between them. This article explains how to set up file access between Linux (Fedora 33) and Windows 10 using Samba and mount.cifs.

Samba is the Linux implementation of the SMB/CIFS protocol, allowing direct access to shared folders and printers over a network. Mount.cifs is part of the Samba suite and allows you to mount the CIFS filesystem under Linux.

Caution: These instructions are for sharing files within your private local network or in a virtualized host-only network between a Linux host machine and a virtualized Windows guest. Don’t consider this article a guideline for your corporate network, as it doesn’t implement the necessary cybersecurity considerations.

Access Linux from Windows

This section explains how to access a user’s Linux home directory from Windows File Explorer.

1. Install and configure Samba

Start on your Linux system by installing Samba:

dnf install samba

Samba is a system daemon, and its configuration file is located in /etc/samba/smb.conf. Its default configuration should work. If not, this minimal configuration should do the job:

[global]
        workgroup = SAMBA
        server string = %h server (Samba %v)
        invalid users = root
        security = user
[homes]
        comment = Home Directories
        browseable = no
        valid users = %S
        writable = yes

You can find a detailed description of the parameters in the smb.conf section of the project’s website.

2. Modify LinuxSE

If your Linux distribution is protected by SELinux (as Fedora is), you have to enable Samba to be able to access the user’s home directory:

setsebool -P samba_enable_home_dirs on

Check that the value is set by typing:

getsebool samba_enable_home_dirs

Your output should look like this:

3. Enable your user

Samba uses a set of users and passwords that have permission to connect. Add your Linux user to the set by typing:

smbpasswd -a <your-user>

You will be prompted for a password. This is a completely new password; it is not the current password for your account. Enter the password you want to use to log in to Samba.

To get a list of allowed user types:

pdbedit -L -v

Remove a user by typing:

smbpasswd -x <user-name>

4. Start Samba

Because Samba is a system daemon, you can start it on Fedora with:

systemctl start smb

This starts Samba for the current session. If you want Samba to start automatically on system startup, enter:

systemctl enable smb

On some systems, the Samba daemon is registered as smbd.

4. Configure the firewall

By default, Samba is blocked by your firewall. Allow Samba to access the network permanently by configuring the firewall.

You can do it on the command line with:

firewall-cmd --add-service=samba --permanent

Or you do it graphically with the firewall-config tool:

5. Access Samba from Windows

In Windows, open File Explorer. On the address line, type in two backslashes followed by your Linux machine’s address (IP address or hostname):

You will be prompted for your login information. Type in the username and password combination from step 3. You should now be able to access your home directory on your Linux machine:

Access Windows from Linux

The following steps explain how to access a shared Windows folder from Linux. To implement them, you need Administrator rights on your Windows user account.

1. Enable file sharing

Open the Network and Sharing Center either by clicking on the

Windows Button > Settings > Network & Internet

or by right-clicking the little monitor icon on the bottom-right of your taskbar:

In the window that opens, find the connection you want to use and note its profile. I used Ethernet 3, which is tagged as a Public network.

Caution: Consider changing your local machine’s connection profile to Private if your PC is frequently connected to public networks.

Remember your network profile and click on Change advanced sharing settings:

Select the profile that corresponds to your connection and turn on network discovery and file and printer sharing:

2. Define a shared folder

Open the context menu by right-clicking on the folder you want to share, navigate to Give access to, and select Specific people… :

Check whether your current username is on the list. Click on Share to tag this folder as shared:

You can display a list of all shared folders by entering \\localhost in File Explorer’s address line:

Shared folders

Image by:

<p class=»rtecenter»><sup>(Stephan Avenwedde, <a href=»https://opensource.com/%3Ca%20href%3D»https://creativecommons.org/licenses/by-sa/4.0/» rel=»ugc»>https://creativecommons.org/licenses/by-sa/4.0/» target=»_blank»>CC BY-SA 4.0</a>)</sup></p>

3. Mount the shared folder under Linux

Go back to your Linux system, open a command shell, and create a new folder where you want to mount the Windows share:

mkdir ~/WindowsShare

Mounting Windows shares is done with mount.cifs, which should be installed by default. To mount your shared folder temporarily, use:

sudo mount.cifs //<address-of-windows-pc>/MySharedFolder ~/WindowsShare/ -o user=<Windows-user>,uid=$UID

In this command:

  • <address-of-windows-pc> is the Windows PC’s address info (IP or hostname)
  • <Windows-user>is the user that is allowed to access the shared folder (from step 2)

You will be prompted for your Windows password. Enter it, and you will be able to access the shared folder on Windows with your normal Linux user.

To unmount the shared folder:

sudo umount ~/WindowsShare/

You can also mount a Windows shared folder on system startup. Follow these steps to configure your system accordingly.

Summary

This shows how to establish temporary shared folder access that must be renewed after each boot. It is relatively easy to modify this configuration for permanent access. I often switch back and forth between different systems, so I consider it incredibly practical to set up direct file access.

This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.

This is a complete tutorial to show you how to share folders over the local network between Windows and Ubuntu.

Do you have multiple devices in your home? Do you have to use Flash Drive or SD card to transfer data from Ubuntu to another computer? Do you find it annoying? We know you do. Because we don’t want you to waste your precious time while you can transfer your files, documents, and other large stuff quickly and easily, over the local network. It’s one-time setup and then with some clicks you will be able to share files between Ubuntu and Windows or any other Linux system. And don’t worry it’s easy and takes only a little time.

One more thing to add, while we performed this tutorial on Ubuntu, this tutorial should be valid for any other Linux OS.

Share folder on local network in Ubuntu

Share files between Windows and Linux on local network

If you are using Ubuntu, there are two ways you can share your local files over the local network to access it from Windows or other Linux computers.

  1. Share it for everyone’s access on local network, without password
  2. Password protect the folders for restricted access

We’ll see both methods in this post and will let you decide which one you would prefer to use.

Method 1. Share folders on local network without password

You’ll have to do some settings on both Windows and Ubuntu.

Enable sharing on Ubuntu

To share a folder on the local network in Ubuntu, right click on the desired folder and select Local Network Share:

Share folder over LAN in ubuntu 14.04

Don’t see Local Network Share option?

Possible troubleshoot: If you do not see the option of Local Network Share in right click menu, open a terminal and use the following command to install nautlius-share:

sudo apt-get install nautilus-share

You’ll need to restart Nautilus. Either log out and log in back or use the command below:

nautilus -q

When you click on Local Network Share, you will see the option of sharing the folder. Just check the option of Share this folder:

Possible troubleshoot: If you are prompted about Sharing service not being installed, like in the screenshot below, just click on Install service and follow the instructions.

Sharing service in Ubuntu

When you check the option of Share this folder, you’ll see option of Create Share available for you. You can also allow other users to edit the files in the shared folder. Option for guest access can be checked as well.

You’ll see that the folder icon have been changed to show that it has been shared. To stop sharing a folder, just uncheck the Share this folder option.

Now access the shared folder on Windows machine.

Step 2: Enable sharing on Windows

On Windows, right click on “This PC” or “My Computer”, and select “Add a new connection”.

Adding New Connection

Adding New Connection

Click on “next” button.

Adding New Connection

Adding New Connection

Now it’s time to enter server address and the name of folder which we’ve shared. Please enter in following format.

You can find your server’s address, i.e. IP address of Linux machine by entering ip a command.

In my case, IP address of Linux machine is 192.168.0.102 and folder I’ve shared is share.

Ip Address

Ip Address

Now add the location in the following manner:

Entering Server Address

Entering Server Address

Now you will see this screen, just click next.

Adding New Connection

Adding New Connection

Now, you can access the shared folder in “This PC” or “My Computer” under “Network Location” section.

New Shared Folder

New Shared Folder

Now this was the easy way out. This provides access to anyone on your local network to access these files. 

In normal condition, you should prefer this. I mean, devices on your home network should be generally known devices. But this could not be the case always. What if you want only certain people to access it?

This is where Samba server comes in picture. We’ll see that in the second part of the tutorial.

2. Share the folders on local network in Ubuntu with password protection

To do this, we need to configure Samba server. Actually, we did use Samba in the previous part of this tutorial. We just did not emphasize on it. Before we go on seeing how to set up Samba server for local network sharing in Ubuntu, let’s first have a quick look on what actually is Samba.

What is Samba?

Samba is the software package that allows you to share files, documents and printers across a network, irrespective of whether you are using Linux, Windows and Mac. It’s available for all major platforms and can work tremendously nice in all of them. Quoting from Wikipedia:

Samba a free software re-implementation of the SMB/CIFS networking protocol, and was originally developed by Andrew Tridgell. As of version 3, Samba provides file and print services for various Windows Clients and can integrate with a Windows Server domain, either as a Primary Domain Controller (PDC) or as a domain member. It can also be part an Active Directory domain.

Install Samba server on Ubuntu

You can easily install Samba on you Ubuntu box. Before installing update your system so that you can install any available updates.

sudo apt-get update && sudo apt-get upgrade

Now install Samba serer and few other required stuffs with the following command:

sudo apt-get install samba samba-common system-config-samba python-glade2

Once you’ve installed Samba server, it’s time to configure Samba from the graphical interface window to share files.

Configure Samba server on Ubuntu

Open Samba Configuration tool from the dash:

Setup Samba in Linux/Ubuntu

Go to Preference->Server Settings. Although the default settings are good and may be same you need. But you may need to make change to it in some cases.

Now in Server Settings you’ve two tabs, ‘Basic’ and ‘Security’. Under Basic tab you’ve the following options that mean:

  • Workgroup – This is the name of the Workgroup of the computer you want to connect to. For example, if you want to connect to a Windows computer so you will enter the workgroup name of Windows computer, and in Windows you already have the same workgroup name as is set by default in Samba Server Settings. But if you have a different workgroup name on Windows then you will enter that workgroup name in this field. (In Windows 7 to get the workgroup name, right-click Computer icon and go to Properties, there you’ll see Windows Workgroup name.)
  • Description – This is the name of your computer as seen by others. Don’t use spaces or non-internet friendly characters.
setting up samba server

Allowing ‘Guests’ is not advisable so there is no reason to change security settings. Keep as it is.

Samba Security security settings

It is all done! You’ve setup Samba Server. We are not far from sharing our first folder on network.

Create a system user for network file sharing

We will now create a system user for sharing file on network. This is how simple it is.

  • Go to System Settings.
  • Under Systems Settings Click User Accounts.
  • Click unlock to Enable + (plus) icon.
  • Click + (plus) icon to create a new system user.
create system user account in Ubuntu/Linux

Now as you can see the above image, you can enter ‘Full name’. As you enter ‘Full name’ Username will be taken as Full name automatically. Because we are creating this user to share files so we will assign Account Type to ‘Standard‘.

Done above steps? Click add. You have created a system user. The user is not yet activated so we will activate it by setting up password for this account. Make sure Users accounts panel is unlocked. Click Account disabled and type a new password, then confirm password and click Change.

activate system user in Ubuntu/Linux

Yipee… Upto now we have installed and configured Samba and We have created a System user to share files on network from the account and we have activated our newly created account, too. Now We will move to Samba for the last step of configuring everything, then we will share a folder.

Add new Samba user

Open Samba and click Samba Users under Preference. Fill up the the simple dialogue. Here are couple of details about the fields:

Unix Username – In this case I am selecting the user that I just created.

Windows Username – You will enter this username when you are accessing from Windows Machine.

Samba Password – You will enter this password when you are accessing from Windows Machine.

samba user setting

Once you’ve done click OK. Now take a deep breath. You have successfully created a network with the help of Samba. Now restart the network or Samba services and ready to share files with other machines.

sudo restart smbd && sudo restart nmbd

Share folders or files over the network

To share files with Samba it’s simple with graphical user interface. Click the Plus icon in Samba and you will get dialogue like this:

share files and folders over network with samba

Complete the fields. In ‘Directory‘ browse the folder you want to share. Here are the details about the fields you will see here:

  • Share name is the name of the folder that other would see.
  • Description is simply about the content you are sharing on network.
  • Writable You shared folders are ‘read only’ by default. You can set them to writable if you want others on network to change them.
  • Visible As the name suggests when you click Visible, the shared folder will be visible to the people on network.

Now you can set permissions for the folder you are sharing. To do this click ‘Access’ tab and check the users you want to share the folder with. When you select Allow access to everyone, the folder will be accessible to everyone on the network.

setting up permissions for sharing folder on network

Finally click OK to complete the sharing. Now the folder is shared with the people you want. You have completed sharing file on network. Is there everything left? Yes! How to remove the folders from the network?

Remove shared folders

We will also need to remove some of the folders after sometime from network. It is very simple and here is how we can do that.

remove shared folder from network

This is all done! We can also share files over network using terminal but that would not be as easy as this one. If you request for command line sharing then I will write a tutorial on how to share files over network with command line in Linux.

So, how do you find this tutorial to share files on local network in Ubuntu? I hope with this tutorial you can easily share files between Ubuntu and Windows. If you have questions or suggestions, feel free to ask it in the comment box below.

This tutorial was requested by Kalc. If you would like, you can request your own tutorial. We would be happy to help you out along with other readers facing the same issue.

With inputs from Abhishek Prakash.

У вас дома есть несколько устройств? Нужно ли использовать флэш-диск или SD-карту для переноса данных с Ubuntu на другой компьютер? Находите ли вы это раздражающим? Мы знаем, что это так. Поэтому мы не хотим, чтобы вы тратили свое драгоценное время, в то время как вы можете передавать свои файлы, документы и другие большие вещи быстро и легко, по локальной сети. Это одноразовая настройка, а затем с помощью нескольких щелчков мыши вы сможете обмениваться файлами между Ubuntu и Windows или любой другой системой Linux. И не волнуйтесь, это легко и займет всего немного времени.

Также стоит добавить, что это руководство должно быть полезно для любой версии ОС Linux.

Общие папки в локальной сети в Ubuntu

Если вы используете Ubuntu, есть два способа поделиться своими локальными файлами по локальной сети, чтобы получить доступ к ним с Windows или других компьютеров с Linux.

  1. Для всех, кто имеет доступ к локальной сети, без пароля. Не совсем безопасный способ, но некоторым он действительно нужен, например, если необходимо очень быстро открыть доступ и времени на настройку ограниченного доступа нет.
  2. С паролем, защищающим папки для ограниченного доступа. Этот способ наиболее рекомендуем для всех, кто предпочитает конфиденциальность при передаче данных в локальной сети, поскольку доступ будет открыт только для ограниченного круга людей.

Мы рассмотрим оба метода в этой статье и дадим вам возможность решить, какой из них вы предпочитаете использовать.

Метод 1. Общий доступ к папкам в локальной сети без пароля

Вам придется выполнить некоторые настройки как в Windows, так и в Ubuntu.

Разрешение на совместное использование в Убунту

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

Не видите опцию локального сетевого ресурса?

Когда вы нажимаете на Локальный сетевой ресурс, вы увидите опцию общего доступа к папке. Просто отметьте опцию Общий доступ к этой папке:

Поиск и устранение неисправностей: Если у вас появится сообщение о том, что служба Sharing service не устанавливается, как показано на скриншоте ниже, просто нажмите кнопку Установить службу и следуйте инструкциям.

Когда вы отметите опцию Общий доступ к этой папке, вы увидите опцию Создать общий доступ, доступную для вас. Вы также можете разрешить другим пользователям редактировать файлы в общей папке. Также можно отметить опцию гостевого доступа.

Вы увидите, что значок папки был изменен, чтобы показать, что она была совместно использована. Чтобы остановить общий доступ к папке, просто снимите флажок Общий доступ к этой папке.

Теперь нужно получить доступ к общей папке на машине Windows.

Шаг 2: Включение совместного доступа в Windows

В Windows щелкните правой кнопкой мыши на «Этот Компьютер» или «Мой компьютер» и выберите «Добавить новое соединение».

Добавление нового соединения

Нажмите на кнопку «Далее».

Добавление нового соединения

Теперь пришло время ввести адрес сервера и имя папки, к которой мы предоставили общий доступ. Пожалуйста, введите в следующем формате.

Вы можете найти адрес вашего сервера, т.е. IP-адрес машины с Linux, введя команду ip a.

В моем случае IP-адрес машины с Linux равен 192.168.0.102, а папка, к которой я предоставил общий доступ, является общей.

Ip-адрес

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

Ввод адреса сервера

Теперь вы увидите этот экран, просто щелкните дальше.

Добавление нового соединения

Теперь вы можете получить доступ к общей папке в разделе «Этот ПК» или «Мой компьютер» в разделе «Сетевое расположение».

Новая общая папка

Это был простой способ. Он обеспечивает доступ к этим файлам любому человеку в вашей локальной сети.

По-хорошему вы должны предусмотреть это. Устройства в домашней сети должны быть общеизвестными. Но так может быть не всегда. Что, если вы хотите, чтобы к ним имели доступ только определенные люди?

Вот здесь и появляется Samba-сервер. Рассмотрим его во второй части урока.

2. Общий доступ к папкам в локальной сети в Ubuntu с помощью парольной защиты

Для этого нам необходимо настроить сервер Samba. На самом деле, мы использовали Samba в предыдущей части этого руководства. Мы просто не делали на этом акцент. Прежде чем мы перейдем к рассмотрению вопроса о том, как настроить Samba-сервер для совместного использования локальной сети в Ubuntu, давайте сначала посмотрим, чем на самом деле является Samba.

Что такое Самба?

Samba — это пакет программного обеспечения, позволяющий обмениваться файлами, документами и принтерами по сети, независимо от того, используете ли вы Linux, Windows и Mac. Он доступен для всех основных платформ и может отлично работать на них всех. Цитирование из Википедии:

Samba — пакет программ, которые позволяют обращаться к сетевым дискам и принтерам на различных операционных системах по протоколуSMB/CIFS. Имеет клиентскую и серверную части. Является свободным программным обеспечением, выпущена под лицензией GPL.

Инсталляция сервера Samba на Ubuntu

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

sudo apt-get update && sudo apt-get upgrade

Теперь установите Samba server и несколько других необходимых вещей с помощью следующей команды:

sudo apt-get install samba samba-common system-config-samba python-glade2

После установки сервера Samba пришло время настроить Samba из окна графического интерфейса на общий доступ к файлам.

Настройка сервера Samba в Ubuntu

Откройте инструмент Samba Configuration из тире:

Перейдите в Параметры -> Настройки сервера. Хотя настройки по умолчанию хороши и могут быть такими же, как вам нужно. Но в некоторых случаях вам может понадобиться внести изменения.

В Параметрах сервера у вас есть две вкладки, ‘Basic’ и ‘Security’. В закладке Basic у вас есть следующие опции:

  • Рабочая группа — это название рабочей группы компьютера, к которому вы хотите подключиться. Например, если вы хотите подключиться к компьютеру с Windows, то введете имя рабочей группы компьютера с Windows, а в Windows у вас уже есть то же имя рабочей группы, которое установлено по умолчанию в Настройках сервера Samba. Но если у вас другое имя рабочей группы в Windows, то вы введете его в это поле. (В Windows 7, чтобы получить имя рабочей группы, щелкните правой кнопкой мыши значок Этот компьютер и перейдите в Свойства, там вы увидите имя рабочей группы Windows).
  • Описание — Это название вашего компьютера, как его видят другие. Не используйте пробелы или неинтернет-доброжелательные символы.

Разрешение ‘Гости’ не рекомендуется, поэтому нет причин изменять настройки безопасности. Оставьте все как есть.

Готово! Вы установили Samba-сервер. Мы недалеко от того, чтобы поделиться нашей первой папкой в сети.

Создание системного пользователя для совместного использования файлов в сети

Теперь мы создадим системного пользователя для совместного использования файлов в сети. Это очень просто.

  • Перейдите в раздел «Системные настройки».
  • В разделе Системные настройки нажмите Учетные записи пользователей.
  • Нажмите кнопку разблокировки, чтобы включить значок +.
  • Нажмите значок + (плюс), чтобы создать нового пользователя системы.

Теперь, как вы видите на изображении выше, вы можете ввести «Полное имя». При вводе ‘Полное имя’ Имя пользователя будет автоматически воспринято как ‘Полное имя’. Потому что мы создаем этого пользователя для совместного использования файлов, поэтому мы назначим тип аккаунта ‘Стандартный’.

Выполнили шаги, описанные выше? Идем дальше. Нажмите «Добавить».

Вы создали пользователя системы. Пользователь еще не активирован, поэтому мы активируем его, установив пароль для этой учетной записи. Убедитесь, что панель учетных записей пользователей разблокирована. Нажмите Аккаунт отключен и введите новый пароль, затем подтвердите пароль и нажмите Изменить.

Отлично! Мы установили и настроили Samba, мы создали системного пользователя для обмена файлами в сети с этой учетной записи, и мы активировали нашу только что созданную учетную запись. Теперь мы перейдем на Samba для последнего шага настройки общего доступа, затем мы предоставим общий доступ к папке.

Добавление нового пользователя Samba

Откройте Samba и нажмите Samba Users в разделе Preferences (Предпочтения). Заполните простую форму. Вот пара подробностей о полях формы:

Unix Username — В данном случае я выбираю пользователя, которого только что создал.

Имя пользователя Windows — Вы вводите это имя пользователя при доступе из компьютера на Windows

Samba Password — Вы введете этот пароль, когда захотите иметь доступ из компьютера на Windows.

После того, как вы закончите, нажмите OK. Теперь сделайте глубокий вдох. Вы успешно создали сеть с помощью Samba. Теперь перезапустите сеть или службы Samba и будьте готовы к обмену файлами с другими компьютерами.

sudo restart smbd && sudo restart nmbd

Общий доступ к папкам или файлам по сети

Обмениваться файлами с Samba очень просто с помощью графического интерфейса пользователя. Нажмите на иконку «Плюс» в Samba и вы получите такой диалог:

Заполните поля. В ‘Directory’ выберите папку, к которой вы хотите предоставить общий доступ. Здесь вы найдете подробную информацию о полях, которые увидите:

  • Share name — это имя папки, которую увидит другой пользователь.
  • Description простое описание содержимого, к которому вы предоставляете общий доступ в сети.
  • Writable. Общие папки по умолчанию ‘только для чтения’. Вы можете установить их в режим «writable», если хотите, чтобы другие пользователи в сети изменили их.
  • Visible. Как следует из названия, когда вы нажимаете Visible, общая папка будет видна людям в сети.

Теперь вы можете установить разрешения для папки, к которой вы предоставляете общий доступ. Для этого перейдите на вкладку «Доступ» и отметьте пользователей, которым вы хотите предоставить общий доступ к папке. Когда вы выберете Разрешить доступ всем, папка будет доступна всем в сети.

Наконец, нажмите OK для завершения обмена. Теперь папка открыта всем желающим. Вы завершили предоставление общего доступа к папке в сети. И все? Да! А как удалить папки из сети?

Удаление общих папок

Нам также иногда нужно будет удалить некоторые папки через некоторое время из сети. Это очень просто, и вот как мы можем это сделать.

Готово! Мы также можем обмениваться файлами по сети с помощью терминала, но это настраивается не так просто, как это было в графическом интерфейсе. Если вы зададите вопросы по доступу к файлам из командной строки, то я напишу учебное пособие о том, как обмениваться файлами по сети с помощью терминала в Linux.

Итак, как вам небольшое руководство о том, как делиться файлами по локальной сети в Linux? Я надеюсь, что с помощью него вы сможете легко обмениваться файлами между Ubuntu и Windows. Если у вас есть вопросы или предложения, не стесняйтесь задавать их в поле для комментариев ниже.

Новости Ubuntu Linux в Telegram

Телеграм канал об Ubuntu и Linux! 🐧 Здесь вы найдёте свежие новости, полезные советы, инструкции, а также обсуждения новых функций и обновлений. Подписывайтесь, чтобы изучать Linux, оптимизировать систему и делиться опытом.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как изменить частоту микрофона на windows 10
  • Windows edit path variable
  • Удаленное управление компьютером windows бесплатно
  • File roller альтернатива в windows
  • Как исправить ошибку 0x80072f8f 0x20000 при обновлении windows через media creation tool