What is samba share in linux

Getting started with Samba for interoperability

The Samba suite helps you to easily share files between Linux and Windows systems. This first article of two teaches you how and where to begin with interoperability.

Getting started with sharing

File shares are important for collaboration in any network. In this series of articles, I will show you how Samba can help you set up and serve file shares on Linux servers that are accessible from both Linux and Windows clients.

Before we dive in and set up file shares, let’s cover what Samba is and what it can do for you.

Great Linux resources

Samba is a suite of applications that implements the Server Message Block (SMB) protocol. Many operating systems, including Microsoft Windows, use the SMB protocol for client-server networking. Samba enables Linux / Unix machines to communicate with Windows machines in a network.

Samba is open source software. Originally, Samba was developed in 1991 for fast and secure file and print share for all clients using the SMB protocol. Since then it has evolved and added more capabilities. Today Samba provides a suite of applications enabling seamless networking and interoperability between *nix and Windows.

Install the Samba packages

In this example, I’m using CentOS 8 with the hostname centos as my Samba server with an IP address of 192.168.1.122. The only package you will need to install is Samba, but I would like to include other client tools like samba-common and samba-client to test out our shares later.

# yum install samba samba-client samba-common -y

Create a directory to share and set its permissions

Once you’ve installed the required packages on the server, let’s create a directory and provide the required permissions on the directory. Create a directory called share on our root directory. You can name this directory anything you want to, and give it read, write and execute permissions. In this example, we will rely on the Samba configuration to control read, write access to the shared directory.

# mkdir /share # chmod -R 777 /share

Now that we have installed necessary packages, it’s time to configure the shared directory. The configuration file is located under /etc/samba . Using your favorite text editor, append the following to /etc/samba/smb.conf . Leave the rest of the configuration file as is and this should be good for our setup.

# vim /etc/samba/smb.conf [myshare] comment = My share path = /share read only = No

I have created a share called myshare and provided a path to the share, which in our case is located at /share . I then gave it read/write permissions with read only = No . There are many other configuration parameters that you may pass here, but for our setup these settings are good.

Читайте также:  Acer aspire one d260 linux

Check the Samba configuration

Samba provides a tool to check our configuration file. We can check if our configuration file has any errors by using the testparm command.

Next, we need to create a Samba user account, so that Samba can communicate in Samba sessions with shares. The smbpasswd command has several functions depending on if you run the command as root or as a standard user. If you issue smbpasswd without any arguments as a non-root user, by default smbpasswd will change the current logged in user’s Samba password. When you run smbpasswd command as root , you will be able to create new Samba accounts. You can create a Samba account only for existing Linux user accounts.

# smbpasswd -a user New SMB password: Retype new SMB password:

We need to configure SELinux on the /share directory so the Samba service has proper permissions.

# semanage fcontext -a -t samba_share_t "/share(/.*)?" # restorecon -R -v /share

Next, we need to enable and start the smb and nmb services.

# systemctl enable smb # systemctl start smb #systemctl enable nmb #systemctl start nmb

If you have firewalld running on your server, we need to configure it to allow Samba traffic. You can do so by using the firewall-cmd command. Don’t forget to make those changes permanent and reload firewalld .

Now we have our services enabled and started. We can check to see if the share is available from the server by using the smbclient tool. This is the reason I have installed the Samba client tools on the local machine. The command uses the following syntax:

# smbclient -U user -L 192.168.1.122 Enter SAMBA\user's password:

Let’s check if we can access the share by issuing the following command on the server:

# smbclient -U user //192.168.1.122/myshare Enter SAMBA\user's password: Try "help" to get a list of possible commands. smb: \>

We have installed and configured the Samba file share service on our Linux server. We were able to access those shares on the local machine. In the next article, we will set up one Linux client and one Windows 10 client to access share we just created.

[ Want to learn more about Linux system administration? Take a Red Hat system administration course. ]

Источник

How to share files with Samba

Samba provides easy, flexible, cross-platform, and open source collaboration across your organization.

File system

Career advice

The Samba project provides file sharing and print services for computers on a network. It uses the Server Message Block and Common Internet File System (SMB/CIFS) protocol, so the services created by running Samba are available to Linux, macOS, and Windows clients. It’s an essential service to run in organizations that support multiple operating systems, and it’s even useful on homogenous networks.

It’s not difficult to set up, and all you need is at least one server you want to designate as a file-share host (it doesn’t have to be rack mounted and could even be a dedicated workstation). For client access, Samba is either built into the operating system or easily installed from a repository.

Читайте также:  Linux asus eee pc 901

Install Samba

On your designated Samba server, install the Samba package:

This command also installs the samba-common-tools and samba-libs packages.

Next, start the SMB and NMB daemons. The SMB daemon manages most Samba services, while the NMB daemon provides NetBIOS services. Here are the commands:

$ systemctl enable --now smb $ systemctl enable --now nmb

That’s the installation. All that’s left is a little configuration.

Configure your firewall

Make sure that your file-share server is accessible over your network by adding the samba service to your firewall config:

$ sudo systemctl enable --now firewalld $ sudo firewall-cmd --list-services cockpit dhcpv6-client ssh $ sudo firewall-cmd --add-service samba success

Configure Samba

Create a directory on the server to hold your shared files and folders, and change the SELinux context to samba_share_t :

$ sudo mkdir /sambashare $ sudo chcon -t samba_share_t /sambashare/

To configure shares and users, edit the /etc/samba/smb.conf file. The default file has several good examples of common options, including provisions for shared printers and home directories.

There’s a global section, which defines a workgroup. I arbitrarily set mine to SAMBA . I have no other existing workgroups on my network, so the workgroup hardly matters for my setup. If your organization has a specific workgroup structure, then follow that.

[global] workgroup = SAMBA security = user passdb backend = tdbsam . 

By default, your Samba server’s NetBIOS name is the server’s Linux hostname. If you don’t have DNS configured on your local network, you can use the server’s IP address when contacting the Samba server.

[ Download the Linux networking cheat sheet to get a list of Linux utilities and commands for managing servers and networks. ]

Create a shared location

To create a new share location, add a section to the /etc/samba/smb.conf configuration file with these two definitions:

[sambashare] path = /sambashare read only = No

Источник

Настройка Samba

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

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

Что такое Samba?

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

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

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

Linux

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

Читайте также:  Firebird classic on linux

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[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” @ (“собака”).

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

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

Источник

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