Samba daemons in linux

How to Setup Samba Server in RHEL, Rocky Linux and AlmaLinux

Sharing files is an essential part of server administration. It allows sharing of resources across the network which are needed by users to carry out their tasks. One of the widely used file-sharing software is Samba.

Samba, a re-implementation of the popular SMB (server message block) protocol, is a stable and free application that allows sharing of files and print services across a network. The software is installed on a central Linux server from which shared files can be accessed from both Linux and Windows systems.

In this guide, we will walk you through the installation of the Samba Server on RHEL-based distributions such as CentOS Stream, Rocky Linux, and AlmaLinux.

Step 1: Install Samba on Linux

To get started out with Samba, install the Samba core packages including the client package:

$ sudo dnf install samba samba-common samba-client

Install-Samba in Linux

The command installs the packages specified along with the dependencies as displayed on the output. After the installation is complete, you will get a summary of all the packages that have been installed.

Samba Installation Completes

Step 2: Create and Configure Samba Shares

Once all the samba packages have been installed, the next step is to configure the samba shares. A samba share is simply a directory that is going to be shared across client systems in the network.

Here, we are going to create a samba share called /data in the /srv/tecmint/ directory path.

$ sudo mkdir -p /srv/tecmint/data

Next, we will assign permissions and ownership as follows.

$ sudo chmod -R 755 /srv/tecmint/data $ sudo chown -R nobody:nobody /srv/tecmint/data $ sudo chcon -t samba_share_t /srv/tecmint/data

Create Samba Share Directory

Next, we are going to make some configurations in the smb.conf configuration file which is Samba’s main configuration file. But before we do so, we will back up the file by renaming it with a different file extension.

$ sudo mv /etc/samba/smb.conf /etc/samba/smb.conf.bak

Next, we are going to create a new configuration file.

We will define policies on who can access the samba share by adding the lines shown in the configuration file.

[global] workgroup = WORKGROUP server string = Samba Server %v netbios name = rocky-8 security = user map to guest = bad user dns proxy = no ntlm auth = true [Public] path = /srv/tecmint/data browsable =yes writable = yes guest ok = yes read only = no

Save and exit the configuration file.

To verify the configurations made, run the command:

Verify Samba Configuration

Next, start and enable Samba daemons as shown.

$ sudo systemctl start smb $ sudo systemctl enable smb $ sudo systemctl start nmb $ sudo systemctl enable nmb

Be sure to confirm that both the smb and nmb daemons are running.

$ sudo systemctl status smb $ sudo systemctl status nmb

Verify Samba Status

To enable access to samba share from remote Windows systems, you need to open the samba protocol on the firewall.

$ sudo firewall-cmd --permanent --add-service=samba $ sudo firewall-cmd --reload $ sudo firewall-cmd --list-services

Step 3: Accessing Samba Share from Windows

Thus far, we have installed samba and configured our samba share. We are now ready to access it remotely. To do this on a Windows client, press the Windows logo key + R to launch the Run dialog.

Читайте также:  Виртуальная машина линукс или виндовс

In the textfield provided, enter the samba server’s IP address as shown:

Access Samba Share from Windows

The following window labeled ‘Public’ will pop up. Remember, this is the directory that points to our samba share in the /srv/tecmint/data directory.

Access Samba Share Directory in Windows

Currently, our directory is empty as we have not created any files. So, we will head back to our terminal and create a few files in the samba share directory.

$ cd /srv/tecmint/data $ sudo touch file.txt

Now, we will navigate to the ‘Public‘ folder where the files we created earlier will be displayed.

Access Samba Share Files in Windows

Perfect. We have successfully managed to access our samba share. However, our directory is accessible to anyone and everybody can edit and delete files at will, which is not recommended especially if you plan to host sensitive files.

In the next step, we will demonstrate how you can create and configure a secure samba share directory.

Step 4: Secure Samba Share Directory

First, we will create a new samba user.

Next, we will configure a password for the samba user. This is the password that will be used during authentication.

Create Samba User

Next, we will create a new group for our secure samba share and add the new samba user.

$ sudo groupadd smb_group $ sudo usermod -g smb_group smbuser

Thereafter, create yet another samba share which will be securely accessed. In our case, we have created another directory in the same path as the

$ sudo mkdir -p /srv/tecmint/private

Then configure the file permissions for the samba share

$ sudo chmod -R 770 /srv/tecmint/private $ sudo chcon -t samba_share_t /srv/tecmint/private $ sudo chown -R root:smb_group /srv/tecmint/private

Once again, access the Samba configuration file.

Add these lines to define to secure samba share.

[Private] path = /srv/tecmint/private valid users = @smb_group guest ok = no writable = no browsable = yes

Save the changes and exit.

Finally, restart all the samba daemons as shown.

$ sudo systemctl restart smb $ sudo systemctl restart nmb

When you access your server this time around, you will notice an additional ‘Private‘ folder. To access the folder, you will be required to authenticate with the Samba user’s credentials. Provide the username and password of the user you created in the previous step and click ‘OK’.

Samba User Authentication Samba Private Share Directory

Step 5: Accessing Samba Share from Linux Client

To access the share from a Linux client, first, ensure that the Samba client package is installed.

$ sudo dnf install samba-client

Then use the smbclient command as follows

# smbclient ‘\2.168.43.121\private’ -U smbuser

Access Samba Share from Linux

And this concludes this guide on setting up Samba on RHEL, CentOS Stream, Rocky Linux, and AlmaLinux. Your feedback on this guide will be highly appreciated.

Читайте также:  Linux dev disk by label

Источник

Linux.yaroslavl.ru

Если вы спешите, то вы можете запустить демоны Samba вручную. Как пользователь root, просто введите следующие команды:

# /usr/local/samba/bin/smbd -D # /usr/local/samba/bin/nmbd -D

С этого момента, Samba будет запущена на вашей системе и готова для установки соедиений.

Чтобы запустить процессы Samba как отдельные демоны, вам необходимо добавить команды, перечисленные в предыдущей секции, в ваш стандартный скрипт запуска в Unix. Это зависит от того, имеете ли вы систему типа BSD Unix или System V Unix.

При стиле BSD Unix, вам необходимо добавить следующие строки в файл rc.local, который обычно находится в директориях /etc или /etc/rc.d :

if [ -x /usr/local/samba/bin/smbd]; then echo "Starting smbd. " /usr/local/samba/bin/smbd -D echo "Starting nmbd. " /usr/local/samba/bin/nmbd -D fi

Этот код достаточно прост; он проверяет, имеет ли файл smbd разрешение на запуск и если имеет, то он запускает каждый демон Samba при загрузке.

С System V придется поработать больше. System V обычно использует скрипты для запуска и остановки демонов в системе. Поэтому, вам придется указать Samba каким образом ему работать при запуске и остановке. Вы можете изменить содержание директории /etc/rc.local и добавить что-то похожее на данную программу под именем smb:

#!/bin/sh # Contains the "killproc" function on Red Hat Linux ./etc/rc.d/init.d/functions PATH="/usr/local/samba/bin:$PATH" case $1 in 'start') echo "Starting smbd. " smbd -D echo "Starting nmbd. " nmbd -D ;; 'stop') echo "Stopping smbd and nmbd. " killproc smbd killproc nmbd rm -f /usr/local/samba/var/locks/smbd.pid rm -f /usr/local/samba/var/locks/nmbd.pid ;; *) echo "usage: smb " ;; esac

При помощи этого скрипта вы можете запускать службу SMB при помощи следующих команд:

# /etc/rc.local/smb start Starting smbd. Starting nmbd. # /etc/rc.local/smb stop Stopping smbd and nmbd.

Inetd – это супер демон Internet в UNIX . Он слушает порты, описанные в / etc / services и запускает соответствующую программу для данного порта, которая определена в файле / etc / inetd . conf . Смысл этого заключается в том, что вы можете иметь большое число демонов, готовых отвечать на запросы, но они не обязательно должны быть запущены. В место этого inetd слушает за остальных. Выгода заключается в том, что для создания нового процесса необходимо выполнить немного операций. Это удобно, если один или два пользователя на вашем компьютере имеют слишком много запущенных демонов. Это также полезно для проведения обновления без разрыва установленных соединений.

Если вы желаете запустить через inetd, для начала откройте /etc/services в текстовом редакторе. Ели вы до сих пор не добавили следующие линии, сделаете это:

netbios-ssn 139/tcp netbios-ns 137/udp

Далее, отредактируйте /etc/inetd.conf. Взгляните на следующие две строки и добавте их, если они отсутствуют. Если вы уже имеете строки с smbd и nmbd в файле, отредактируйте их в соответствии с заново установленными smbd и nmbd. Ваша разновидность Unix-а может использовать немного другой синтакс файла; используйте существующие записи и станицы документации inetd.conf в качестве руководства:

netbios-ssn stream tcp nowait root /usr/local/samba/bin/smbd smbd netbios-ns dgram udp wait root /usr/local/samba/bin/nmbd nmbd

Окончательно, убейте любые процессы smbd или nmbd и пошлите процессу inetd сигнал HUP. (Демон inetd заново прочитает свой конфигурационный файл по сигналу HUP.) Чтобы сделать это, используйте команду ps для того, чтобы найти ID процесса, после чего пошлите сигнал при помощи следующей команды:

После этого Samba должен работать.

© 1999, O’Reilly & Associates, Inc.

Источник

Samba daemons in linux

Есть два демона SMB /usr/sbin/smbd и /usr/sbin/nmbd. В большинстве дистрибутивов Linux, они запускаются, останавливаются и перезапускаются через стартовый скрипт, расположенный в /etc/rc.d/init.d/smb, на который созданы символьные ссылки с соответствующих уровней запуска.

Если вы не будете использовать стандартные стартовые скрипты, то Вы можете запустить демоны Samba из inetd или как автономные процессы. Samba будет отвечать чуть быстрее когда она запущена как автономный процесс, чем в случае когда она запускается из inetd.

В некоторых случаях вы должны проверить наличие в файле /etc/services примерно таких строк:

netbios-ns 137/tcp nbns netbios-ns 137/udp nbns netbios-dgm 138/tcp nbdgm netbios-dgm 138/udp nbdgm netbios-ssn 139/tcp nbssn

Убедитесь, что все они не закомментированы. В зависимости от вашего дистрибутива, вам может даже нужно будет добавить их в этот файл. Samba не сможет привязаться к соответствующим портам пока этих строк не будет в файле /etc/services.

Для запуска демонов из inetd, поместите следующие строки в конфигурационный файл inetd, /etc/inetd.conf:

# SAMBA NetBIOS services (for PC file and print sharing) netbios-ssn stream tcp nowait root /usr/sbin/smbd smbd netbios-ns dgram udp wait root /usr/sbin/nmbd nmbd

Затем перезапустите демон inetd выполнив команду:

kill -HUP 1 `cat /var/run/inetd.pid`

Для запуска демонов из системных стартовых скриптов, поместите следующий скрипт в файл /etc/rc.d/init.d/smb (для большинства дистрибутивов) и создайте на него символические ссылки с именами указанными в комментариях:

#!/bin/sh # # /etc/rc.d/init.d/smb - запускает и останавливает сервисы SMB # # Следующие файлы должны быть символическими ссылками на этот файл: # symlinks: # /etc/rc.d/rc1.d/K35smb (Убивает сервисы SMB при выключении # /etc/rc.d/rc3.d/S91smb (Запускает сервисы SMB в многопользовательском режиме) # /etc/rc.d/rc6.d/K35smb (Убивает сервисы SMB при перезагрузке) # # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ $ = "no" ] && exit 0 # See how we were called. case "$1" in start) echo -n "Starting SMB services: " daemon smbd -D daemon nmbd -D echo touch /var/lock/subsys/smb ;; stop) echo -n "Shutting down SMB services: " killproc smbd killproc nmbd rm -f /var/lock/subsys/smb echo "" ;; *) echo "Usage: smb " exit 1 esac

Если при старте Samba вы получаете сообщение в котором говорится, что демон не может подключится к порту 139, то вероятно у вас уже есть запущенные процессы Samba, которые не были завершены. Посмотрите список процессов (используя команду ‘ps auxww | grep mbd’) для того, чтобы определить есть ли еще запущенные сервисы Samba.

Источник

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