Samba share folder linux to windows

If you work with different operating systems, it's handy to be able to share files between them.

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:

Sebool

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:

firewall-config

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):

Accessing Linux machine from Windows

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:

Accessing Linux machine from Windows

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:

Open network and sharing center

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:

Change advanced sharing settings

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

Network sharing settings

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… :

Give access

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

Tag as shared

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

Shared folders

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.

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

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.

# yum install samba-client samba-common  -y

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.

# smbclient -U user -L 192.168.1.122

Enter SAMBAuser's password:

        Sharename       Type      Comment
        ---------       ----      -------
        print$          Disk      Printer Drivers
        myshare         Disk      my share
        IPC$            IPC       IPC Service (Samba 4.9.1)
        user      Disk      Home Directories

Reconnecting with SMB1 for workgroup listing.

        Server               Comment
        ---------            -------

        Workgroup            Master
        ---------            -------
        SAMBA                SAMBA-SERVER

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.

# mkdir /mnt/myshare

Now, mount the share.

# mount -t cifs -o username=user //192.168.1.122/myshare /mnt/share

Password for user@//192.168.1.122/myshare:  ********

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

# df -h

Persistent mount

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.

# vim /etc/fstab

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

//192.168.1.122/myshare /mnt/share cifs username=user,password=password,_netdev 0  0

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.

//192.168.1.122/myshare /mnt/share cifs credentials=/home/user/.cred,_netdev 0 0

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.

# vim /home/user/.cred

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

username=user
password=password

Finally, mount all filesystems.

# mount -a

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:

PS > $password = Read-Host -AsSecureString
PS > New-LocalUser -Name “user” -Password $password

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.

Browsing to the Samba share.

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:

PS > NET USE M: \centosmyshare
A Samba share mapped to the M: drive.

Wrap up

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

Updated: 03/12/2022 by

The easiest and most reliable way to share files between a Linux and Windows computer on the same local area network is to use the Samba file-sharing protocol. All modern versions of Windows come with Samba installed, and Samba is installed by default on most distributions of Linux.

Create a shared folder on Windows

First, create a shared folder on your Windows computer.

Note

Following the steps below, creates a shared folder on your Windows computer that lets you access files in that folder on your Linux computer. With the right permissions you can also copy, edit, and delete files in that folder from your Linux computer.

  1. Open the Control Panel.
  2. Select the Network and Sharing Options or Network and Sharing Center option.
  3. Click the Change advanced sharing settings link in the left navigation menu.
  4. Click the Turn on Network Discovery and Turn on File and Print Sharing options.
  5. Click the Save changes button at the bottom of the Advanced sharing settings window.

Now, create a new folder to share or choose an existing folder that you want to share.

  1. Right-click the folder and select Properties.
  2. Go to the Sharing tab.
  3. If you want to share the folder with another Windows account, click the Share button, add the account to grant permission to access the shared folder, and click the Share button.

Note

If you shared the folder with another Windows account, you need to click the Advanced Sharing button, then click the Permissions button. Select the account, check the Allow box for the Change or Modify permission, and click OK.

  1. Click the Advanced Sharing button.
  2. On the Advanced Sharing window, check the box for Share this folder and click OK.
  3. The network path for the folder is now displayed above the Share button, indicating that it is now a shared folder. For example, it may look something like \YOURCOMPUTERNAMEUsersYourUserNameShareFolderName. Make a note of this network folder path to use later on your Linux machine.

Access a Windows shared folder from Linux using Konqueror

Many Linux distributions use the KDE desktop environment and the Konqueror file manager/browser. If you’re using this, you can follow these steps to access your Windows shared folder.

  1. Click the K menu icon.
  2. Select Internet -> Konqueror.
  3. In the Konqueror window that opens, click the Network Folders link, or type remote:/ in the address bar and press Enter.
  4. Click the Samba Shares icon.
  5. Click the icon of your Windows Home workgroup.
  6. Click the Workgroup icon.
  7. Click the icon for your computer.
  8. When prompted, enter the username and password for the Windows account that created the share.
  9. Click OK.

Access a Windows shared folder from Linux using Nautilus

Many Linux distributions, especially those that use the GNOME desktop environment, use the Nautilus file manager. If you’re using this, you can follow these steps to access your Windows shared folder.

  1. Open Nautilus.
  2. From the File menu, select Connect to Server.
  3. In the Service type drop-down box, select Windows share.
  4. In the Server field, enter the name of your computer.
  5. Click Connect.

Alternatively, in the Nautilus address bar, you can type smb://ComputerName/ShareName and press Enter. For example, when you created your Windows Share if the share name was listed as:

\YOURCOMPUTERNAMEUsersYourUserNameShareFolderName

Type smb://YOURCOMPUTERNAME/Users/YourUserName/ShareFolderName and press Enter. Note the smb: at the beginning, in Linux, use forward slashes instead of backslashes.

Access a Windows shared folder from Linux using the command line

You can also access your Windows shared folder from the Linux command line using the smbclient program.

  1. Open a terminal.
  2. Type smbclient at the command prompt.
  3. If you receive a «Usage:» message, smbclient is installed, and you can skip to the next step. However, if the command is not found, you need to install smbclient. Follow these steps to install it.
    1. If you use the apt package manager, the default on Linux systems such as Ubuntu or Debian, you can use the sudo apt-get install smbclient command.
    2. If you use the yum package manager, the default on Linux systems, such as CentOS, you can use the sudo yum install samba-client command.
    3. You can also download the Samba client directly at www.samba.org/samba/download/, which might be useful to you if you need or want to compile the program from the source code.
  4. With smbclient installed, you can connect to your Windows share using the command smbclient //ComputerName/ShareName -U Username. For instance, if your Windows username is Fred, and your Windows share network name is \YOURCOMPUTERNAMEUsersYourUserNameShareFolderName, use the command smbclient //YOURCOMPUTERNAME/Users/YourUserName/ShareFolderName -U Fred. Notice that the Linux command uses forward slashes instead of backslashes).
  5. Enter your password.
  6. Once authenticated, you are placed at an smb: > prompt.
  7. Here, you can use the ls or dir command to list files.
  8. Use the command get filename.ext to transfer a file named filename.ext from your Windows share to your Linux machine, for example. If the file name contains spaces, make sure to enclose it in double quotes, for example: get «My new file.txt».
  9. Type help for a listing of further commands.
  10. Type quit or exit to return to the command prompt.

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:

Share folders in Ubuntu and Windows

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.

sharing the folders in Ubuntu

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.

Your home network might have a few Windows machines on the ground floor, a Mac in an upstairs bedroom, a PocketPC on a nightstand, and a Linux box or two in the basement, all networked with a generic router. For all the devices in this familiar family setup, or even a scenario with thousands of users, the Samba suite is an ideal solution for file and print sharing.

Several cross-platform file and print-sharing solutions exist, but Samba and the SMB/CIFS protocol may be the easiest to implement in a home networking environment. Windows machines and Macs come with the functionality to work with with Samba out of the box, and you should only need to install a single Samba package for Linux machines. GNOME and KDE offer Samba client functionality built in to their default file managers, Nautilus and Konqueror, respectively.

We’ll focus on configuring and using Samba for file and print-sharing in a typical home network with Linux and Windows machines. You can choose from several Samba configuration GUIs, but we’ll go the old-fashioned route and point our text editors to smb.conf. The configuration file is commonly found at /etc/samba/smb.conf or /usr/local/samba/lib/smb.conf. Note that you will need to be root to edit these, or use sudo.

Samba will run on nearly any Unix-like system and can be found in the repositories of just about every Linux distribution. Begin by using your distribution’s package manager to make sure it is installed.

Configuring Samba

Samba is a very mature and complex package, so its configuration file can be long and complicated. You will have to trust that your distribution supplied you with a reasonably sound default configuration and focus on changing just a few lines in smb.conf to make sure they are appropriate for the purposes of a home network. If you want to know more about any line, consult man smb.conf.

Remember that any line in the configuration file preceded by a semicolon (;) or hash mark (#) is a comment and will not be recognized as an active setting. To activate the line, remove the semicolon or hash. It’s a good idea to add your own comments preceded by one of these characters so that you will remember the logic behind your configuration the next time you load smb.conf.

The first option to consider is Samba’s security level. This line will appear under the [global] section of smb.conf, where all Samba-wide configuration is done. The other sections, addressed later in this article, relate to specific Samba services (shared resources). The security level will most likely be set to the value user and look like this:

security = user

For a home network, you may want to consider setting this to share. The main difference is that with the user setting you will be required to log into the Samba server before you can browse its resources. This is a wise precaution on untrusted networks, but will be inconvenient when using resources you would like your entire household to have access to, such as a printer. With share enabled, you can still require users to authenticate themselves with a password to access particular resources.

While still in the [global] section, let’s move on to printers. If you use the Common UNIX Printing System (CUPS) (which most distributions default to), the only thing you need to do to have Samba recognize your printers is set the following lines accordingly:


printing = cups
printcap name = cups

Since you may be configuring these printers (and perhaps other resources) to be accessible without user authentication, it is very important that you restrict access to only known and trusted hosts – the computers in your household. Consult your router’s manual for instructions on assigning specific IP addresses to each computer in your home network. Once you have a list of trusted hosts, enter them into the following lines in the [global] section:


hosts allow = computer1 computer2 computerN
hosts deny = ALL

Although you have specified that ALL hosts be denied, any host listed on the hosts allow line will still be given access. The format of the IP addresses assigned to each computer by your router will vary. For instance, if machines on your local network are given addresses of the format 192.168.0.x, the following lines will restrict Samba access to local hosts:

hosts allow = 192.168.0.
hosts deny = ALL

Note that the final digit of the IP address was left off on the hosts allow line. This specifies that any IP address in that range be allowed. For additional security against external access, look into blocking Samba ports with a firewall.

Sharing directories and printers

It’s time to move beyond [global] and configure specific shared resources. Begin with the [homes] section. By default, your distribution may have this section configured to allow users to access their home directory on the machine running the Samba server.

If you have security = share set, this feature may not work as expected and users may be presented with home directories without logging in. If you are the only one with a home directory on the machine running the Samba server anyway, which is likely in a home network environment, it is advisable to remove or comment out (using hash marks or semicolons) the [homes] section and add any useful directories as shared resources individually later on.

Now you can begin sharing specific directories. Use this as a template for a publicly shared folder for which it is not necessary for users to be authenticated:

[Share Name]
path = /location/of/directory
guest ok = yes
browseable = yes
read only = no

Share Name is whatever title you choose (to the client accessing your server, this will appear to be the name of the shared directory). The guest ok = yes line is what specifies this share as publicly accessible. The browseable = yes line will make the share appear available to all users. Set browseable = no to force users to manually type in the share name to access it. Of course, you can set read only = yes to restrict users from make changes to the directory remotely.

Use this as a template for private shares that users must enter a password to access:

[Share Name]
path = /location/of/directory
valid users = user
read only = yes
browseable = no

Here, user is the user name on the machine running the Samba server of the person with access privileges to the share. Use these two templates to add shares for all the files users may want to access from the server machine.

Your server should be fully configured now. With what you added to the defaults provided by your distribution, your completed smb.conf should look something like this:

[global]
security = share
workgroup = HOME
server string = %h server
log file = /var/log/samba/log.%m
max log size = 1000
dns proxy = No
hosts allow = 192.168.0.
hosts deny = ALL
printing = cups
printcap name = cups

[printers]
path = /var/spool/samba
printable = Yes
browseable = No

[print$]
path = /var/lib/samba/printers

[Public Directory]
path = /Public/Files
guest ok = yes
read only = no
browseable = yes

[Private Directory]
path = /private/files/
valid users = me
read only = yes
browseable = no

Before you leave the server machine you have a few more quick chores. First, enter any users that will be accessing the Samba server into the following command:

smbpasswd -a user

You will be prompted to enter a Samba password for each user. You can change the password at any time by logging in as the desired user and running smbpasswd. Now restart your Samba server using this command:

/etc/init.d/samba restart

Accessing Samba shares from Windows clients

Head over to a Windows machine to try out your new setup. Your new server should appear in Windows’ My Network Places (look for the shortcut on your desktop, by default). Alternatively, open the Start menu and click “Run…”, then enter:

server

Replacing server with the name or IP address of the machine running your Samba server. A Windows Explorer window with the browseable shares from your server should open up. If you’ve made a non-browseable share, access it using this link:

servershare name

Is is easy to make shared directories more accessible. In Windows XP, right click on the share in Explorer and choose “Map Network Drive…” You will be able to assign them a drive letter, such as Z:, so that they may be easily found in My Computer, even after a reboot.

In my testing on Windows XP with the security level set to share, printers are automatically be detected and available to use from the Windows machine. With user level security set, it was necessary to log into the server in a Windows Explorer window before trying to print. Your experience on other versions of Windows may vary.

Accessing SMB/CIFS shares from other Linux machines

Samba and Windows shares can be easily accessed from the default file managers of both Gnome and KDE. We’ll begin with accessing shares from Nautilus in Gnome. Open Nautilus and go to File -> Connect to Server.

Choose “Windows share” from the listbox and enter the server name or IP address of your Samba server. You can also click the “Browse Network” button and look in the “Windows Network” directory to search for the server manually. Click “Connect” and a Nautilus window will open with the browseable resources of your Samba server.

Accessing Samba shares with Konqueror is just as simple. To browse for your server, enter the URL remote:/ in Konqueror. For direct access, type the URL of the server in directly in this format:

smb://user@server/share

Note that user and share are optional criteria.

Configuring printers over Samba is similarly easy in both these desktop environments. In Gnome, go to System -> Administration -> Printing. In the printer configuration application, select Printer -> Add printer. You will be prompted for your password. In the add printer wizard, select “Network Printer” and then “Windows Printer SMB” from the listbox. You will be prompted for a user name and password on your Samba server. Identify your Host and Printer on the Samba server and then move on to the next screen. Select your printer model and then click Apply.

To do the same in KDE, open the configuration center by launching the command kcontrol. Navigate to the Printers module and go to Add -> Add Printer/Class… In the resulting dialog, click Next and then select “SMB shared printer (Windows).” Click Next again and configure the username and password of a “Normal account,” if using user level security. Click Next another time and then Scan to browse for your Samba server.

Alternatively, enter the server details manually. On the next screen, select your printer model from the list. Click through the next few screens and give your networked printer a title to finish up.

Troubleshooting

If you’ve experienced any problems getting any of this functionality to work, turn to the Samba troubleshooting checklist. A quick trick borrowed from that document for testing your Samba configuration file for obvious errors is to run the following command:

testparm smb.conf

Again, the exact path of your smb.conf may vary by distribution.

We have only explored basic Samba functionality here, tailored for a home network. More extreme usage scenarios are addressed in detail in the Samba by example guide.

Пожалуй нет ни одного офиса, в котором не применялись бы общие ресурсы локальной сети, будь то папки или принтеры. Крупные и средние компании используют возможности Active Directory, компании поменьше — используют штатные средства ОС Windows или Samba, но на серверах под управлением ОС Linux. Рассмотрим все случаи.

Как настроить Samba?

  • Что такое Samba?
  • Как настроить общую папку
  • Как настроить общую папку в Linux
  • Как настроить общую папку в Windows
  • Как подключиться к общей папке
  • Как подключиться к общей папке Linux
  • Как подключиться к общей папке Windows
  • Как создать общий сетевой ресурс в Samba

Что такое Samba?

Samba — серверное приложение, реализующее доступ клиентских терминалов к папкам, принтерам и дискам про протоколу SMB/CIFS.

Описание структуры Samba

Настройка общих папок

Linux

Установка и настройка Samba-сервер для Ubuntu выполняется следующими этапами.

Обновляем информацию о репозиториях и устанавливаем обновления для существующих пакетов в системе:

apt-get update && apt-get upgrade

Устанавливаем пакет Samba:

apt-get install -y samba samba-client

Создадим резервную копию файла конфигурации:

cp /etc/samba/smb.conf /etc/samba/smb.conf_sample

Создадим директории для файлов, например в каталоге /media:

mkdir /media/samba

Важно! По умолчанию, директория /media располагается в корне системы /, для нее редко создается свой раздел. По этой причине возможно переполнение корневого раздела. Во избежание этой неприятной ситуации, рекомендуем монтировать отдельный жесткий диск в /media/samba.

Создаем каталог для всех пользователей:

mkdir /media/samba/public

Изменим права доступа к каталогу:

chmod -R 0755 /media/samba/public

Также следует воспользоваться командой chown для смены владельца и/или группы.

Создаем директорию для ограниченного круга лиц:

mkdir /media/samba/private

С помощью системных инструментов создадим группу пользователей:

groupadd smbgrp

Добавляем пользователей Samba:

useradd user1

Созданных пользователей добавляем в группу:

usermod -aG smbgrp user1

Изменим группу, которой принадлежит приватная директория:

chgrp smbgrp /media/samba/private

С помощью инструментов Samba создадим пароль для добавленного пользователя:

smbpasswd -a user1

С помощью текстового редактора, например, nano, редактируем конфигурационный файл samba:

nano /etc/samba/smb.conf

Удаляем все строки из файла. Вставляем следующие:

[global]
workgroup = WORKGROUP
security = user
map to guest = bad user
wins support = no
dns proxy = no
[public]
path = /media/samba/public
guest ok = yes
force user = nobody
browsable = yes
writable = yes
[private]
path = /media/samba/private
valid users = @smbgrp
guest ok = no
browsable = yes
writable = yes

Сохраняем используя сочетание Ctrl + X, затем нажимаем Y и Enter.

Объясним значения строк. конфигурационный файл состоит из трех секций:

global — данная секция отвечает за общие настройки Samba-сервера;

public и private — секции описания настроек директорий общего доступа.

В секции global присутствуют пять параметров:

  • workgroup — рабочая группа. Для упрощения работы пользователей WORKGROUP указывается, как группа по умолчанию. Если в вашей сети имя рабочей группы изменено, то следует изменить это значение и для Samba;
  • security — уровень безопасности сервера. Значение user означает авторизацию по паре логин/пароль;
  • map to guest — параметр определяет способ обработки запросов. Значение bad user означает, что запросы с неправильным паролем будут отклонены, даже если такое имя пользователя существует;
  • wins support — включить или выключить поддержку WINS;
  • dns proxy — возможность проксирования запросов к DNS.

Настройки директорий выполняются в соответствующих секциях:

path — полный путь до директории на жестком диске;

guest ok — возможность доступа к каталогу без пароля (гостевой);

browsable — показывать ли каталог (“шару”) на сервере среди прочих. Если параметр установлен как “no”, то доступ будет возможен по полному пути, например ip-addresshidden_directory;

force user — пользователь от которого ведется работа с каталогом. Для повышения безопасности сервера, обычно используют nobody. Главное, не использовать пользователя root — это небезопасно.

writable — установка значения как “yes” позволяет пользователю выполнять действия над файлами внутри каталога — переименование, добавление, удаление, перемещение в подкаталог и копирование;

valid users — список пользователей у которых есть доступ к каталогу. Если пользователей несколько, их имена указываются через запятую. Если необходим доступ для пользователей принадлежащих группе, перед именем группы устанавливается символ ”at” @ (“собака”).

Важно! Имя директории общего доступа, отображаемое пользователям, равно имени секции в которой оно описано.

Проверяем настройки с помощью команды:

testparm -s

Перезапускаем сервер:

service smbd restart

service nmbd restart

Настроим межсетевой экран. Для этого в правилах откроем TCP-порты 139 и 445, а также UDP-порты 137 и 138, но только для тех подсетей, которым доверяете. Для указания собственного диапазона адресов, замените значение после ключа “-s”:

iptables -A INPUT -p tcp -m tcp --dport 445 -s 10.0.0.0/24 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 139 -s 10.0.0.0/24 -j ACCEPT

iptables -A INPUT -p udp -m udp --dport 137 -s 10.0.0.0/24 -j ACCEPT
iptables -A INPUT -p udp -m udp --dport 138 -s 10.0.0.0/24 -j ACCEPT

Для сохранения правил и применения их после перезагрузки сервера следует воспользоваться пакетом iptables-persistent. Установим его:

apt-get install iptables-persistent

Входе установки пакета, программа предложит запомнить существующие правила iptables. Подтверждаем это действие.

Для проверки существующих правил используем:

iptables -L

Windows

По аналогии с Linux, настроим общий доступ к папкам public и private, но в ОС Windows.

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

Панель управления → Сеть → Центр управления сетями и общим доступом → Расширенные настройки общего доступа.

В обновленном окне открываем раздел “Все сети” и ищем секцию “Общий доступ с парольной защитой”. Устанавливаем параметр в положение “Отключить общий доступ с парольной защитой”. Для сохранения значений параметра кликаем по кнопке “Сохранить изменения”.

Отключаем общий доступ с парольной защитой

Теперь откроем доступ к самому каталогу. Кликаем по папке правой кнопкой мыши, в контекстном меню выбираем “Свойства”. Открываем вкладку “Доступ” и кликаем по “Расширенная настройка”.

Выбираем расширенную настройку

В открывшемся окне расширенных настроек общего доступа отмечаем галочкой “Открыть общий доступ к этой папке”, в поле “Имя общего ресурса” указываем название, которое будет отображено пользователям. Кликаем по кнопке “Разрешения”.

В открывшемся окне, в группах пользователей выбираем “Все”, а в разрешениях для группы, устанавливаем галку “Полный доступ”. Нажимаем “OK” в этом и остальных окнах.

Выбираем саму группу и разрешения для группы

В окне свойств папки public кликаем по кнопке “Общий доступ”.

Общий доступ к файлам в Samba | Serverspace

В открывшемся окне добавляем пользователя “Все”, а также делегируем права на “Чтение и запись”. Кликаем по кнопке “Поделиться”.

Выбираем права и делимся ими с пользователями

В обновленном окне нажимаем “Готово”.

Нажимаем готово

Настроим папку общего доступа, но для ограниченного круга лиц.

Кликаем правой кнопкой мыши по папке, выбираем “Свойства”.

В открывшемся окне переходим на вкладку “Доступ”. Кликаем по кнопке “Расширенные настройки”.

В новом открывшемся окне, устанавливаем галку “Открыть общий доступ к этой папке”. Затем кликаем по кнопке “Разрешения”.

Открываем общий доступ к этой папке

В открывшемся окне, в поле “Группы или пользователи” выбираем “Все” и нажимаем кнопку “Удалить”.

Удаляем пользователя

Таким образом установлен запрет на анонимный доступ к папке.

Окно обновится. Кликаем по кнопке “Добавить”.

В открывшемся окне кликаем по кнопке “Дополнительно”.

Выбираем дополнительные параметры

Окно изменится в размере. Кликаем по кнопке “Поиск”. Двойным кликом выбираем пользователя, которому необходим доступ к этому каталогу, например, buhgalter.

Добавляем пользователя которому нужен доступ к этому каталогу

В открывшемся окне, при желании, можем добавить еще одного пользователя через “Дополнительно” — “Поиск”. Аналогичным образом можно добавить группу пользователей, например, “Администраторы”, при этом следует понимать, что доступ будет предоставлен всем пользователям из этой группы.

При желании добовляем еще одного пользователя

Установим права доступа для пользователя “buhgalter”. Если требуется полный доступ к директории, устанавливаем галку в соответствующем месте.

Пример установки прав для группы пользователей

Нажимая кнопки “OK” возвращаемся к окну свойств папки, в котором кликаем по кнопке “Общий доступ”.

Возвращаемся обратно и выбираем общий доступ

В данном окне необходимо найти и добавить пользователя “бухгалтер”.

Ищем нашего пользователя и добавляем его

В окне выбора пользователей и групп кликаем по кнопке “Дополнительно”.

Выбираем дополнительные параметры

Окно снова изменит свои размеры. Кликаем по кнопке “Поиск”. В найденном ниже списке пользователей и групп выбираем искомого пользователя. Выбираем его двойным кликом.

Выбираем пользователей

В оставшемся окне проверяем правильно ли указан пользователи и нажимаем кнопку “OK”.

Проверяем выбранного пользователя

Устанавливаем требуемый уровень разрешений для пользователя и кликаем по кнопке “Поделиться”.

Добавляем права и делимся ими

Кликаем по кнопке “Готово”.

Теперь папка общего доступа доступна

Подключение к общим папкам

Из Linux

Для подключения к общим папкам из среды Linux требуется установка отдельного программного обеспечения — smbclient. Установим:

sudo apt-get install smbclient

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

smbclient -U <Имя_пользователя> <IP-адрес><Имя_каталога_на_сервере>

Пример:

smbclient -U buhgalter 10.0.0.1public

Для того, Чтобы не вводить эту команду каждый раз, можно настроить монтирование общей директории как сетевого диска. Для этого установим пакет cifs-utils:

sudo apt-get install cifs-utils

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

mount -t cifs -o username=<Имя_пользователя>,password= //<IP-адрес>/<Общий каталог> <Точка монтирования>

Пример:

mount -t cifs -o username=Everyone,password= //10.0.0.1/public /media

Важно! Если требуется подключение к общим папкам расположенным на Windows-сервере, то в для не защищенных паролем директорий, в качестве имени пользователя, следует использовать “Everyone”. Для подключения к Linux-серверу рекомендуем использовать в качестве имени пользователя “nobody”. В случае доступа к защищенным директориям следует использовать те учетные данные, которые вы указали.

Из Windows

Подключение к удаленным папкам из среды Windows выполняется немного иначе. Для этого в проводнике или окне запуска программ (Windows + R), следует использовать следующий шаблон:

<IP-адрес><имя_папки>

Указав просто IP-адрес сервера вы получите список общих папок.

Список общих папок

При подключении к Windows-сервер, система безопасности может потребовать ввод учетных данных. Для подключения к общей открытой папке используем Everyone, а поле пароля оставляем пустым.

Для подключения к общей папке выбираем Everyone и пустое поле для пароля

При подключении к Linux-серверу из ОС Windows, следует использовать указанный ранее шаблон:

<IP-адрес><имя_папки>

или просто адрес сервера:

<IP-адрес>

Как создать общий сетевой ресурс в Samba

Создайте директорию, которую в хотите сделать общей:

mkdir /home/<user_name>/<folder_name></folder_name></user_name>

Создайте бэкап, если что-то пойдет не так:

sudo cp /etc/samba/smb.conf ~

Отредактируйте файл «/etc/samba/smb.conf»:

sudo nano /etc/samba/smb.conf

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

[<folder_name>]
path = /home/<user_name>/<folder_name>
valid users = <user_name>
read only = no</user_name></folder_name></user_name></folder_name>

Заполните файл своими данными, сохраните его и затем закройте

Перезапустим Samba:
sudo service smbd restart

Использую данную команду проверьте вашу директорию smb.conf на ошибки:

testparm

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

sudo apt-get install smbclient
# Просмотр всех общих ресурсов:
smbclient -L //<host_ip_or_name>/<folder_name> -U <user>
# Подключение:
smbclient //<host_ip_or_name>/<folder_name> -U <user></user></folder_name></host_ip_or_name></user></folder_name></host_ip_or_name>

Note 1: Чтобы подключиться к вашему общему сетевому ресурсу используйте имя вашего пользователя () и пароль, который находится «smb:////»
Учтите, что «» значение передается в «[]»,
другими словами, имя общего ресурса, которое вы ввели в «/etc/samba/smb.conf».
Note 2: Группа пользователей samba по умолчанию это — «WORKGROUP».

Although Linux has made some inroads into the desktop market, its origins and future are very much server-based. It is not surprising therefore that Ubuntu has the ability to act as a file server. It is also extremely common for Ubuntu and Windows systems to be used side by side in networked environments. It is a common requirement, therefore, that files on an Ubuntu system be accessible to Linux, UNIX and Windows-based systems over network connections. Similarly, shared folders and printers residing on Windows systems may also need to be accessible from Ubuntu based systems.

Windows systems share resources such as file systems and printers using a protocol known as Server Message Block (SMB). In order for an Ubuntu system to serve such resources over a network to a Windows system and vice versa it must, therefore, support SMB. This is achieved using technology called Samba. In addition to providing integration between Linux and Windows systems, Samba may also be used to provide folder sharing between Linux systems (as an alternative to NFS which was covered in the previous chapter).

In this chapter we will look at the steps necessary to share file system resources and printers on an Ubuntu system with remote Windows and Linux systems, and to access Windows resources from Ubuntu.

1.1  Accessing Windows Resources from the GNOME Desktop

Before getting into more details of Samba sharing, it is worth noting that if all you want to do is access Windows shared folders from within the Ubuntu GNOME desktop then support is already provided within the GNOME Files application. The Files application is located in the dash as highlighted in Figure 23-1:

Figure 23-1

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

Once launched, select the Other Locations option in the left-hand navigation panel followed by the Windows Network icon in the main panel to browse available windows resources:

Figure 23-2

1.2  Samba and Samba Client

Samba allows both Ubuntu resources to be shared with Windows systems and Windows resources to be shared with Ubuntu systems. Ubuntu accesses Windows resources using the Samba client. Ubuntu resources, on the other hand, are shared with Windows systems by installing and configuring the Samba service.

1.3  Installing Samba on an Ubuntu System

The default settings used during the Ubuntu installation process do not typically install the necessary Samba packages. Unless you specifically requested that Samba be installed it is unlikely that you have Samba installed on your system. To check whether Samba is installed, open a terminal window and run the following command:

# apt -qq list samba-common samba smbclient

Any missing packages can be installed using the apt command-line tool:

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

# apt install samba-common samba smbclient

1.4  Configuring the Ubuntu Firewall to Enable Samba

Next, the firewall currently protecting the Ubuntu system needs to be configured to allow Samba traffic.

If you are using the Uncomplicated Firewall (ufw) run the following command:

Alternatively, if you are using firewalld, run the firewall-cmd command as follows:

# firewall-cmd --permanent --add-port={139/tcp,445/tcp}
# firewall-cmd --reload

Before starting the Samba service a number of configuration steps are necessary to define how the Ubuntu system will appear to Windows systems, and the resources which are to be shared with remote clients. The majority of these configuration tasks take place within the /etc/samba/smb. conf file.

1.5  Configuring the smb.conf File

Samba is a highly flexible and configurable system that provides many different options for controlling how resources are shared on Windows networks. This flexibility can lead to the sense that Samba is overly complex to work with. In reality, however, many of the configuration options are not needed by the typical installation, and the learning curve to set up a basic configuration is actually quite short.

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

For the purposes of this chapter we will look at joining an Ubuntu system to a Windows workgroup and setting up a directory as a shared resource that can be accessed by a specific user. This is a configuration known as a standalone Samba server. More advanced configurations such as integrating Samba within an Active Directory environment are also available, though these are outside the scope of this book.

The first step in configuring Samba is to edit the /etc/samba/smb.conf file.

1.5.1  Configuring the [global] Section

The smb.conf file is divided into sections. The first section is the [global] section where settings can be specified that apply to the entire Samba configuration. While these settings are global, each option may be overridden within other sections of the configuration file.

The first task is to define the name of the Windows workgroup on which the Ubuntu resources are to be shared. This is controlled via the workgroup = directive of the [global] section which by default is configured as follows:

Begin by changing this to the actual name of the workgroup if necessary.

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

In addition to the workgroup setting, the other settings indicate that this is a standalone server on which the shared resources will be protected by user passwords. Before moving on to configuring the resources to be shared, other parameters also need to be added to the [global] section as follows:

[global]
.
.
        netbios name = LinuxServer
.
.

The “netbios name” property specifies the name by which the server will be visible to other systems on the network.

1.5.2  Configuring a Shared Resource

The next step is to configure the shared resources (in other words the resources that will be accessible from other systems on the Windows network). In order to achieve this, the section is given a name by which it will be referred to when shared. For example, if we plan to share the /sampleshare directory of our Ubuntu system, we might entitle the section [sampleshare]. In this section a variety of configuration options are possible. For the purposes of this example, however, we will simply define the directory that is to be shared, indicate that the directory is both browsable and writable and declare the resource public so that guest users are able to gain access:

[sampleshare]
        comment = Example Samba share
        path = /sampleshare
        browseable = Yes
        public = yes
        writable = yes

To restrict access to specific users, the “valid users” property may be used, for example:

valid users = demo, bobyoung, marcewing

1.5.3  Removing Unnecessary Shares

The smb.conf file is pre-configured with sections for sharing printers and the home folders of the users on the system. If these resources do not need to be shared, the corresponding sections can be commented out so that they are ignored by Samba. In the following example, the [homes] section has been commented out:

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

.
.
#[homes]
#       comment = Home Directories
#       valid users = %S, %D%w%S
#       browseable = No
#       read only = No
#       inherit acls = Yes
.
.

1.6  Creating a Samba User

Any user that requires access to a Samba shared resource must be configured as a Samba User and assigned a password. This task is achieved using the smbpasswd command-line tool. Consider, for example, that a user named demo is required to be able to access the /sampleshare directory of our Ubuntu system from a Windows system. In order to fulfill this requirement we must add demo as a Samba user as follows:

# smbpasswd -a demo
New SMB password:
Retype new SMB password:
Added user demo.

Now that we have completed the configuration of a very basic Samba server, it is time to test our configuration file and then start the Samba services.

1.7  Testing the smb.conf File

The settings in the smb.conf file may be checked for errors using the testparm command-line tool as follows:

# testparm
Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
WARNING: The "syslog" option is deprecated
Processing section "[printers]"
Processing section "[print$]"
Processing section "[sampleshare]"
Loaded services file OK.
Server role: ROLE_STANDALONE
 
Press enter to see a dump of your service definitions
 
# Global parameters
[global]
	dns proxy = No
	log file = /var/log/samba/log.%m
	map to guest = Bad User
	max log size = 1000
	netbios name = LINUXSERVER
	obey pam restrictions = Yes
	pam password change = Yes
	panic action = /usr/share/samba/panic-action %d
	passwd chat = *Entersnews*spassword:* %nn *Retypesnews*spassword:* %nn *passwordsupdatedssuccessfully* .
	passwd program = /usr/bin/passwd %u
	security = USER
	server role = standalone server
	server string = %h server (Samba, Ubuntu)
	syslog = 0
	unix password sync = Yes
	usershare allow guests = Yes
	wins support = Yes
	idmap config * : backend = tdb
 
[printers]
	browseable = No
	comment = All Printers
	create mask = 0700
	path = /var/spool/samba
	printable = Yes
 
[print$]
	comment = Printer Drivers
	path = /var/lib/samba/printers
 
[sampleshare]
	comment = Example Samba share
	guest ok = Yes
	path = /sampleshare
	read only = No

1.8  Starting the Samba and NetBIOS Name Services

In order for an Ubuntu server to operate within a Windows network both the Samba (SMB) and NetBIOS nameservice (NMB) services must be started. Optionally, also enable the services so that they start each time the system boots:

# systemctl enable smbd
# systemctl start smbd
# systemctl enable nmbd
# systemctl start nmbd

Before attempting to connect from a Windows system, use the smbclient utility to verify that the share is configured:

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

# smbclient -U demo -L localhost 
Enter WORKGROUPdemo's password: 
 
	Sharename       Type      Comment
	---------       ----      -------
	print$          Disk      Printer Drivers
	sampleshare     Disk      Example Samba share
	IPC$            IPC       IPC Service (demo-server2 server (Samba, Ubuntu))
	Officejet_Pro_8600_C7C718_ Printer   
	Officejet_6600_971B9B_ Printer   
Reconnecting with SMB1 for workgroup listing.
 
	Server               Comment
	---------            -------
 
	Workgroup            Master
	---------            -------
	WORKGROUP            LINUXSERVER

1.9  Accessing Samba Shares

Now that the Samba resources are configured and the services are running, it is time to access the shared resource from a Windows system. On a suitable Windows system on the same workgroup as the Ubuntu system, open Windows Explorer and navigate to the Network panel. At this point, explorer should search the network and list any systems using the SMB protocol that it finds. The following figure illustrates an Ubuntu system named LINUXSERVER located using Windows Explorer on a Windows 10 system:

Figure 23-3

Double clicking on the LINUXSERVER host will prompt for the name and password of a user with access privileges. In this case it is the demo account that we configured using the smbpasswd tool:

Figure 23-4

Entering the username and password will result in the shared resources configured for that user appearing in the explorer window, including the previously configured /sampleshare resource:

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

Figure 23-5

Double clicking on the /sampleshare shared resource will display a listing of the files and directories contained therein.

If you are unable to see the Linux system or have problems accessing the shared folder, try mapping the Samba share to a local Windows drive as follows:

  1. Open Windows File Explorer, right-click on the Network entry in the left-hand panel and select Map network drive… from the resulting menu.
  2. From the Map Network Drive dialog, select a drive letter before entering the path to the shared folder. For example:
\LinuxServersampleshare

Enable the checkbox next to Connect using different credentials. If you do not want the drive to be mapped each time you log into the Windows system, turn off the corresponding check box:

Figure 23-6

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

With the settings entered, click on the Finish button to map the drive, entering the username and password for the Samba user configured earlier in the chapter when prompted. After a short delay the content of the Samba share will appear in a new File Explorer window.

1.10  Accessing Windows Shares from Ubuntu

As previously mentioned, Samba is a two way street, allowing not only Windows systems to access files and printers hosted on an Ubuntu system, but also allowing the Ubuntu system to access shared resources on Windows systems. This is achieved using the smbclient package which was installed at the start of this chapter. If it is not currently installed, install it from a terminal window as follows:

Shared resources on a Windows system can be accessed either from the Ubuntu desktop using the Files application, or from the command-line prompt using the smbclient and mount tools. The steps in this section assume that appropriate network sharing settings have been enabled on the Windows system.

To access any shared resources on a Windows system using the GNOME desktop, begin by launching the Files application and selecting the Other Locations option. This will display the screen shown in Figure 23-7 below including an icon for the Windows Network (if one is detected):

Figure 23-7

You are reading a sample chapter from Ubuntu 20.04 Essentials. Buy the full book now in eBook ($14.99) or Print ($36.99) format. Includes 37 chapters. Learn more.

Preview  Buy eBook  Buy Print

Selecting the Windows Network option will display the Windows systems detected on the network and allow access to any shared resources.

Figure 23-8

Alternatively, the Connect to Server option may be used to connect to a specific system. Note that the name or IP address of the remote system must be prefixed by smb:// and may be followed by the path to a specific shared resource, for example:

smb://WinServer10/Documents

1.11  Summary

In this chapter we have looked at how to configure an Ubuntu system to act as both a Samba client and server allowing the sharing of resources with Windows systems. Topics covered included the installation of Samba client and server packages and configuration of Samba as a standalone server.

Ezoic

Samba is a free/open source and popularly used software for sharing files and print services between Unix-like systems including Linux and Windows hosts on the same network.

In this guide, we will show how to setup Samba4 for basic file sharing between a Ubuntu systems and Windows machines. We will cover two possible scenarios: anonymous (unsecure) as well as secure file sharing.

Suggested Read: How to Install Samba4 on CentOS/RHEL 7 for File Sharing on Windows

Note that starting from version 4.0, Samba can be used as an Active Directory (AD) domain controller (DC). We have organized a special series for setting up Samba4 Active Directory Domain Controller, which comprises of key topics under Ubuntu, CentOS, and Windows.

  1. Setting Up Samba4 Active Directory Domain Controller

Install and Configure Samba in Ubuntu

Samba server is available to install from the default Ubuntu repositories using the apt package manager tool as shown.

$ sudo apt install samba samba-common python-dnspython

Once samba server installed, now its time to configure samba server as: unsecure anonymous and secure file sharing.

For this, we need to edit the main Samba configuration file /etc/samba/smb.conf (which explain various configuration directives).

First backup the original samba configuration file as follows.

$ sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.orig

Afterwards, we’ll proceed to configure samba for anonymous and secure file sharing services as explained below.

Important: Before moving any further, ensure that the Windows machine is in the same workgroup which will be configured on the Ubuntu server.

Check Windows Machine WorkGroup Settings

Login into your Windows machine, right click on “This PC” or “My Computer Properties Advanced System Settings Computer Name to verify the workgroup.

Check Windows WorkGroup

Check Windows WorkGroup

Alternatively, open the command prompt and view it by running the command below and look for “workstation domain”.

>net config workstation

Verify Windows WorkGroup

Verify Windows WorkGroup

Once you know your Windows workgroup its time to move ahead and configure samba server for file sharing.

Anonymous Samba File Sharing

First start by creating a shared samba directory where the files will be stored.

$ sudo mkdir -p /srv/samba/anonymous_shares

Then set the appropriate permissions on the directory.

$ sudo chmod -R 0775 /srv/samba/anonymous_shares
$ sudo chown -R nobody:nogroup /srv/samba/anonymous_shares

Now open the configuration file.

$ sudo vi /etc/samba/smb.conf
OR
$ sudo nano /etc/samba/smb.conf

Next edit or modify the directive settings as described below.

global]
	workgroup = WORKGROUP
	netbios name = ubuntu
	security = user
[Anonymous]
	comment = Anonymous File Server Share
	path = /srv/samba/anonymous_shares
	browsable =yes
	writable = yes
	guest ok = yes
	read only = no
	force user = nobody

Now verify current samba settings by running the command below.

$ testparm

Samba Current Configuration Settings

Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
WARNING: The "syslog" option is deprecated
Processing section "[printers]"
Processing section "[print$]"
Processing section "[Shares]"
Loaded services file OK.
Server role: ROLE_STANDALONE

Press enter to see a dump of your service definitions

# Global parameters
[global]
	netbios name = UBUNTU
	server string = %h server (Samba, Ubuntu)
	server role = standalone server
	map to guest = Bad User
	obey pam restrictions = Yes
	pam password change = Yes
	passwd program = /usr/bin/passwd %u
	passwd chat = *Entersnews*spassword:* %nn *Retypesnews*spassword:* %nn *passwordsupdatedssuccessfully* .
	unix password sync = Yes
	syslog = 0
	log file = /var/log/samba/log.%m
	max log size = 1000
	dns proxy = No
	usershare allow guests = Yes
	panic action = /usr/share/samba/panic-action %d
	idmap config * : backend = tdb

[printers]
	comment = All Printers
	path = /var/spool/samba
	create mask = 0700
	printable = Yes
[print$]
	comment = Printer Drivers
	path = /var/lib/samba/printers
	browseable = No
[Anonymous]
	comment = Anonymous File Server Share
	path = /srv/samba/anonymous_shares
	force user = nobody
	read only = No
	guest ok = Yes

Then restart Samba services to effect the above changes.

$ sudo systemctl restart smbd   [Systemd]
$ sudo service smbd restart     [Sys V]

Testing Anonymous Samba File Sharing

Go to the Windows machine, and open “Network” from a Windows Explorer window. Click on the Ubuntu host (TECMINT for our case), or else try to access the samba server using its IP address.

2.168.43.168

Note: Use the ifconfig command to get your Ubuntu server IP address.

Connect to Samba Share

Connect to Samba Share

Then open the Anonymous directory and try to add files in there to share with other users.

Add Files to Samba Share

Add Files to Samba Share

Secure Samba File Sharing

To password-protect a samba share, you need to create a group “smbgrp” and set a password for each user. In this example I use aaronkilik as user and password as “tecmint“.

$ sudo addgroup smbgrp
$ sudo usermod aaronkilik -aG smbgrp
$ sudo smbpasswd -a aaronkilik

Note: The samba security mode: security = user requires clients to enter a username and password to connect to shares.

Samba user accounts are separate from system accounts, however, you can optionally install the libpam-winbind package which is used to sync system users and passwords with the samba user database.

$ sudo apt install libpam-winbind

Then create the secure directory where the shared files will be kept.

$ sudo mkdir -p /srv/samba/secure_shares

Next, set the appropriate permissions on the directory.

$ sudo chmod -R 0770 /srv/samba/secure_shares
$ sudo chown -R root:smbgrp /srv/samba/secure_shares

Now open the configuration file.

$ sudo vi /etc/samba/smb.conf
OR
$ sudo nano /etc/samba/smb.conf

Next edit or modify the directive settings as described below.

[Secure]
	comment = Secure File Server Share
	path =  /srv/samba/secure_shares
	valid users = @smbgrp
	guest ok = no
	writable = yes
	browsable = yes

Just like before, run this command to see your current samba settings.

$ testparm

Samba Current Configuration Settings

Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
WARNING: The "syslog" option is deprecated
Processing section "[printers]"
Processing section "[print$]"
Processing section "[Shares]"
Loaded services file OK.
Server role: ROLE_STANDALONE

Press enter to see a dump of your service definitions

# Global parameters
[global]
	netbios name = UBUNTU
	server string = %h server (Samba, Ubuntu)
	server role = standalone server
	map to guest = Bad User
	obey pam restrictions = Yes
	pam password change = Yes
	passwd program = /usr/bin/passwd %u
	passwd chat = *Entersnews*spassword:* %nn *Retypesnews*spassword:* %nn *passwordsupdatedssuccessfully* .
	unix password sync = Yes
	syslog = 0
	log file = /var/log/samba/log.%m
	max log size = 1000
	dns proxy = No
	usershare allow guests = Yes
	panic action = /usr/share/samba/panic-action %d
	idmap config * : backend = tdb
[printers]
	comment = All Printers
	path = /var/spool/samba
	create mask = 0700
	printable = Yes
[print$]
	comment = Printer Drivers
	path = /var/lib/samba/printers
	browseable = No
[Anonymous]
	comment = Anonymous File Server Share
	path = /srv/samba/anonymous_shares
	force user = nobody
	read only = No
	guest ok = Yes
[Secure]
	comment = Secure File Server Share
	path = /srv/samba/secure_shares
	valid users = @smbgrp
	read only = No

Once you done with the above configurations, restart Samba services to apply the changes.

$ sudo systemctl restart smbd   [Systemd]
$ sudo service smbd restart     [Sys V]

Testing Secure Samba File Sharing

As before, in the Windows machine, and open “Network” from a Windows Explorer window. Click on the Ubuntu host (TECMINT for our case). You may get the error below, if not proceed to the next step.

Connect to Secure Samba Share

Connect to Secure Samba Share

Try to access the server using its IP address, e.g. \192.168.43.168 like this. Then enter the credentials (username and password) for user aaronkilik and click OK.

Samba Share User Login

Samba Share User Login

You’ll now view all the shared directories, click on Secure to open it.

Samba Secure Share

Samba Secure Share

You can securely share some files with other permitted users on the network by dropping them in this directory.

Add Files on Samba Share

Add Files on Samba Share

Enable Samba in UFW Firewall in Ubuntu

If you have UFW firewall enabled/active on your system, you must add the rules to allow Samba to pass through your firewall.

To test this, we’ve used the 192.168.43.0 network scheme. Run the commands below specifying your network address.

$ sudo ufw allow proto udp to any port 137 from 192.168.43.0/24
$ sudo ufw allow proto udp to any port 138 from 192.168.43.0/24
$ sudo ufw allow proto tcp to any port 139 from 192.168.43.0/24
$ sudo ufw allow proto tcp to any port 445 from 192.168.43.0/24

You can also check out these useful articles concerning Samba file sharing on a network.

  1. Setting Up Samba4 Active Directory Domain Controller- Part 1 to 14
  2. How to Mount/Unmount Local and Network (Samba & NFS) Filesystems in Linux
  3. Using ACLs (Access Control Lists) and Mounting Samba / NFS Shares
  4. How to Fix SambaCry Vulnerability (CVE-2017-7494) in Linux Systems

That’s all! In this guide, we showed you how to setup Samba4 for anonymous and secure file sharing between Ubuntu and Windows machines. Use the feedback form below to share any thoughts with us.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

I would like to share a folder from a Linux Guest with a Windows host (with read and write access if possible) in VirtualBox.

I read in these two links: here and here that it’s possible to do this using Samba, but I am a little bit lost and need more information on how to proceed.

So far, I managed to set up two network adapters (one NAT and one host-only) and to install Samba on the Linux guest, but I have the following questions now:

  1. What do I need to type in samba.conf to share a folder from the Linux guest? (the tutorial provided in one of the links above only explains how to share home directories)
  2. Are there any Samba commands that I need to run on the guest to enable sharing?
  3. How do I make sure that these folders are only available to the host OS and not on the Internet?
  4. Once the Linux guest is setup, how do I access each of the individual shared folders from the Windows host? I read that I need to mount a drive on Windows to do this, but do I use Samba logins, or Linux logins, also do I use localhost? or do I need to set up an IP for this?

Thanks!

Community's user avatar

asked Mar 15, 2011 at 20:20

Amelio Vazquez-Reina's user avatar

0

  1. These are examples how you define a share in your smb.conf

    [readonly-share]
       comment = some share
       path = /this/folder/is/shared
       guest ok = no
       browseable = yes
       read only = yes
    
    [read-write-share]
       comment = another share
       path = /this/folder/is/writable
       guest ok = no
       browseable = yes
       read only = no
       create mask = 0777
       directory mask = 0777
       force create mode = 777
       force directory mode = 777
       force security mode = 777
       force directory security mode = 777
    
  2. After you edit smb.conf run «testparm» to check your changes, then let the daemon re-read the config with a «service smbd restart»

  3. (Not sure about this one)
    With a «NAT» and «host-only» virtual network card you should be safe. To reach the guest’s services from any other computer but the host, you would need to set up port forwardings on the host or configure a «bridged» virtual network card.

  4. Authentication type can be set in the smb.conf. The default setting in Ubuntu’s samba conf it to set «security = user», which means that you have to authenticate with a valid useraccount. (unless you have set «guest ok = yes»)

    To access the shares from your Windows Host you have to use the guest’s IP address. VBox NATs are use addresses like «10.0.2.15».
    To reach the share «readonly-share» from the host you can write a URI like this in the File Explorer’s address bar:

    \10.0.2.15readonly-share
    

Oleh Prypin's user avatar

answered Mar 15, 2011 at 23:33

1

In the answer that bytesum gives, readonly-share must not be a full path, but the path stripped of its $HOME part.
I.e.: in my case I was testing to share /home/me/Documents; my machine is named MYMACHINE.
So in Windows7 I had to specify when mapping a network drive:

\MYMACHINEDocuments

note the absence of /home/me.
Problem solved.

answered Feb 20, 2015 at 19:40

Roadowl's user avatar

RoadowlRoadowl

2122 silver badges6 bronze badges

**[Global Section]**
workgroup=WORKGROUP[your workgroup name here mine is"WORKGROUP"]
interfaces=your guest ip here
allow hosts=windows ip here
**[Share Details]**
path=samba share path
browsable=yes
readable=yes

Pierre.Vriens's user avatar

answered Jul 23, 2017 at 7:49

rock's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Samba linux windows не может получить доступ
  • Samba debian не видит сеть windows
  • Sam4s spt 4700 драйвера windows 10
  • Sam4s ellix 50d драйвер windows 10
  • Sam файл как скопировать windows 7