Samba - установка и настройка: различия между версиями

Материал из AlexNook
Перейти к навигацииПерейти к поиску
 
(не показано 11 промежуточных версий этого же участника)
Строка 10: Строка 10:
{{file|/etc/portage/package.use/samba|
{{file|/etc/portage/package.use/samba|
<syntaxhighlight lang="apache" line start="1" line="GESHI_FANCY_LINE_NUMBERS" enclose="div">
<syntaxhighlight lang="apache" line start="1" line="GESHI_FANCY_LINE_NUMBERS" enclose="div">
net-fs/samba acl aio netapi pam readline syslog winbind
net-fs/samba acl pam system-mitkrb5 winbind syslog -regedit
</syntaxhighlight>
</syntaxhighlight>
}}
}}


{{note|Я так же использовал флаг '''server''', но он у меня был установлен глобально. Флаг нужен для активации работы самбы в режиме сервера}}


При этом используются следующие '''USE''' флаги суммарно:
При этом используются следующие '''USE''' флаги суммарно:
Строка 20: Строка 19:
{{USEFlag|extended=yes|
{{USEFlag|extended=yes|
{{EnableFlag|acl}}  
{{EnableFlag|acl}}  
{{EnableFlag|aio}}
{{EnableFlag|system-mitkrb5}}
{{EnableFlag|netapi}}
{{EnableFlag|pam}}  
{{EnableFlag|pam}}  
{{EnableFlag|readline}}
{{EnableFlag|winbind}}
{{EnableFlag|winbind}}
{{EnableFlag|syslog}}}}
{{EnableFlag|syslog}}}}


* '''acl''' - Enables Access Control Lists. The ACL support in Samba uses a patched ext2/ext3, or SGI's XFS in order to function properly as it extends more detailed access to files or directories; much more so than typical *nix GID/UID schemas.
* '''acl''' - Enables Access Control Lists. The ACL support in Samba uses a patched ext2/ext3, or SGI's XFS in order to function properly as it extends more detailed access to files or directories; much more so than typical *nix GID/UID schemas.
* '''aio''' - Enable asynchronous IO support
* '''system-mitkrb5''' Use app-crypt/mit-krb5 instead of app-crypt/heimdal.
* '''netapi''' - Enable building of netapi bits
* '''pam''' - Include support for pluggable authentication modules (PAM). This provides the ability to authenticate users on the Samba Server, which is required if users have to login to your server. The kerberos USE flag is recommended along with this option.
* '''pam''' - Include support for pluggable authentication modules (PAM). This provides the ability to authenticate users on the Samba Server, which is required if users have to login to your server. The kerberos USE flag is recommended along with this option.
* '''readline''' - Link Samba against libreadline. This is highly recommended and should probably not be disabled.
* '''server''' - Enables the server part
* '''syslog''' - для логирования
* '''syslog''' - для логирования
* '''winbind''' - Winbind allows for a unified logon within a Samba environment. It uses a Unix implementation of Windows RPC calls, PAM and the name service switch (supported by the c library) to enable Windows NT domain users to appear and work as Unix users on a Unix system.
* '''winbind''' - Winbind allows for a unified logon within a Samba environment. It uses a Unix implementation of Windows RPC calls, PAM and the name service switch (supported by the c library) to enable Windows NT domain users to appear and work as Unix users on a Unix system.
Строка 38: Строка 32:
Для установки в Gentoo воодим:
Для установки в Gentoo воодим:
{{root|emerge samba}}
{{root|emerge samba}}
{{note|В ядре нужно активировать опцию '''CONFIG_KEY_DH_OPERATIONS'''. Если она не будет активирована, то установщик в конце об этом напомнит. Сделать это можно вот ткт: Security Options --> Diffie-Helman operations on retained keys}}


==Настройка сервера==
==Настройка сервера==
Строка 73: Строка 69:
{{file|/etc/samba/smb.conf|
{{file|/etc/samba/smb.conf|
<syntaxhighlight lang="apache" line start="1" line="GESHI_FANCY_LINE_NUMBERS" enclose="div">
<syntaxhighlight lang="apache" line start="1" line="GESHI_FANCY_LINE_NUMBERS" enclose="div">
# Samba config file created using SWAT
# from 192.168.0.104 (192.168.0.104)
# Date: 2008/09/05 17:00:49


#Глобальные настройки
#======================= Global Settings =====================================
[global]
[global]
        netbios name = Router_a
#рабочая группа домашней виндовой сети
        workgroup = FRC
#Название которое отображается в заголовке окна при заходе на сервер (%v - версия самбы)
        server string = Router_a
#Говорит о типе доступа на сервер. SHARE - это простая "шара", USER - для доступа по реквизитам логин/пароль
#      security = SHARE
        security = User
#Всех гостей интерпритируем как не верных юзеров
        map to guest = Bad User
#Степень подробности логов (от 1 до 10)
        log level = 3
#Путь куда логи сохраняем - %m это имя хоста зашедшего на сервер
        log file = /var/log/samba/log.%m
#Максимальный размер лога в килобайтах
        max log size = 10000
        socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
#Как я понял винда очень не любит когда кто-то выступает в роли мастера и завладевает конектом кроме неё самой
        preferred master = No
        local master = No
#Не использовать прокси
        dns proxy = No
#Интерфейсы, которые слушает демон
        interfaces = 192.168.0.0/24
#Разрешённые к коннекту подсети (отсутствие последней цифры означает что она может быть любой)
        hosts allow = 192.168.0., 192.168.1.


#read / write share
# workgroup = NT-Domain-Name or Workgroup-Name, eg: MIDEARTH
[secret]
  workgroup = FRC
         path = /path/to/secret/readwrite/share
 
# server string is the equivalent of the NT Description field
  server string = Donik Samba Server
 
# Server role. Defines in which mode Samba will operate.
  server role = standalone server
 
# Restrict connections to machines which are on your local network.
  hosts allow = 192.168.0. 10.8.0.
  hosts deny = 0.0.0.0/0
 
#---------------------------------------------------------------
#      !!!READ INFO FOR "bind interfaces only" OPTION!!!      |
#---------------------------------------------------------------
# if you have
#
# bind interfaces only = yes
#      - it would not listen to non-broadcast interfaces (which openvpn tun0 is). This is written in man smb.conf:
#
#              Note that you should not use this parameter for machines that are serving PPP or other intermittent
#              or non-broadcast network interfaces as it will not cope with non-permanent interfaces.
 
 
# If you have multiple network interfaces then you must list them here.
#  interfaces = 192.168.0.0/24
  interfaces = enp3s0 tun0
# To bind all Samba services to the Interfaces list above
  bind interfaces only = no
 
# this tells Samba to use a separate log file for each machine
  log file = /var/log/samba/log.%m
 
# Put a capping on the size of the log files (in Kb).
  max log size = 10000
 
# Level of logging 0-10. 0 is none, 3 is considerable. 1 is the default
  log level = 2
 
 
# Determine the security mode. Others are: ads and domain
  security = User
 
# what to do with user login requests that don.t match a valid UNIX user in some way.
# Never . Means user login requests with an invalid password are rejected.
  map to guest = Never
 
# This sets the NetBIOS name by which a Samba server is known.
  netbios name = Donik
 
# DNS Proxy - tells Samba whether or not to try to resolve NetBIOS names via DNS nslookups
  dns proxy = no
 
#Get rid of error
# "nmbd: Error - should be sent to WINS server"
os level = 255
wins support = Yes
 
# These scripts are used on a domain controller or stand-alone
# machine to add or delete corresponding unix accounts
;  add user script = /usr/sbin/useradd %u
;  add group script = /usr/sbin/groupadd %g
;  add machine script = /usr/sbin/adduser -n -g machines -c Machine -d /dev/null -s /bin/false %u
;  delete user script = /usr/sbin/userdel %u
;  delete user from group script = /usr/sbin/deluser %u %g
;  delete group script = /usr/sbin/groupdel %g
 
 
#============================ Share Definitions ==============================
 
[warez]
        comment = Private files
         path = /mnt/samba
         read only = No
         read only = No
         valid users = username
         valid users = samba
         create mask = 0740
         create mask = 0640
         directory mask = 0750
         directory mask = 0750
         guest ok = no
         guest ok = no
 
#only read share
#[temp]
[public]
#      comment = Temp files
        path = /path/to/public/readable/share
#      path = /mnt/samba/ochakovo/temp
        read only = Yes
#      read only = No
        valid users = username
#      valid users = samba
        guest ok = no
#      create mask = 0600
#      directory mask = 0700
#      guest ok = no
 
#[torrent]
#      comment = Torrents downloading dir
#      path = /mnt/samba/ochakovo/torrents
#      read only = No
#      valid users = samba
#      create mask = 0660
#      directory mask = 0770
#      force group = users
#      guest ok = no
 
#[pub]
#      comment = Public FTP
#      path = /home/ftp/pub
#      read only = No
#      valid users = samba
#      create mask = 0644
#      directory mask = 0755
#      guest ok = no
 
 
 
</syntaxhighlight>
</syntaxhighlight>
}}
}}
Строка 127: Строка 189:


{{root|chmod 750 /path/to/share/samba}}
{{root|chmod 750 /path/to/share/samba}}


===Добавляем польователя шары===
===Добавляем польователя шары===
Строка 136: Строка 197:
{{root|useradd -g primgrp -s /sbin/nologin -G secgrp samba}}
{{root|useradd -g primgrp -s /sbin/nologin -G secgrp samba}}
Тут создаётся пользователь с именем '''samba''' с первчиной (основной) группой '''primgrp''' и допольнительной группой '''secgrp'''  
Тут создаётся пользователь с именем '''samba''' с первчиной (основной) группой '''primgrp''' и допольнительной группой '''secgrp'''  
Например:
{{root|useradd -g warez -s /sbin/nologin -d /mnt/samba  samba}}


Далее даём ему любой сложности рандомный пароль, запоминать который не нужно. Чем сложнее тем лучше =)
Далее даём ему любой сложности рандомный пароль, запоминать который не нужно. Чем сложнее тем лучше =)

Текущая версия на 10:25, 9 ноября 2023

Логотип Samba

Samba - это программа работающая по протоколу smb или cifs, способная обеспечивать взаимодействие систем на базе Linux с системами гед стоит ОС от Microsoft.

Рассмотрим установку Samba и настройку серверной её части для работы в сети Microsoft. То есть мы имеем сервер с установленным на него ОС Gentoo куда и хотим поставить Samba, которая позволит всем компьютерам локальной сети видеть на сервере с ОС Gentoo "расшаренные" папки в стиле того как это делает ОС Windows.

Установка

Сперва вносим USE флаги в конфиг:

File: /etc/portage/package.use/samba
net-fs/samba acl pam system-mitkrb5 winbind syslog -regedit


При этом используются следующие USE флаги суммарно:

Use Flags: acl system-mitkrb5 pam winbind syslog (?)

  • acl - Enables Access Control Lists. The ACL support in Samba uses a patched ext2/ext3, or SGI's XFS in order to function properly as it extends more detailed access to files or directories; much more so than typical *nix GID/UID schemas.
  • system-mitkrb5 Use app-crypt/mit-krb5 instead of app-crypt/heimdal.
  • pam - Include support for pluggable authentication modules (PAM). This provides the ability to authenticate users on the Samba Server, which is required if users have to login to your server. The kerberos USE flag is recommended along with this option.
  • syslog - для логирования
  • winbind - Winbind allows for a unified logon within a Samba environment. It uses a Unix implementation of Windows RPC calls, PAM and the name service switch (supported by the c library) to enable Windows NT domain users to appear and work as Unix users on a Unix system.

Для установки в Gentoo воодим:

emerge samba
Note: В ядре нужно активировать опцию CONFIG_KEY_DH_OPERATIONS. Если она не будет активирована, то установщик в конце об этом напомнит. Сделать это можно вот ткт: Security Options --> Diffie-Helman operations on retained keys

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

Для использования NetBIOS'а Windows'ом возможно имеет смысл поправить строку в файле

File: /etc/nsswitch.conf
hosts: files dns wins

добавив туда слово wins

Для начала скопируем полностью пример конфигурационного файла с коментариями в папку, где должен находится рабочий конфиг.

cp /etc/samba/smb.conf.example /etc/samba/smb.conf

или сразу создадим кофиг командой

nano -w /etc/samba/smb.conf

В файле /etc/samba/smb.conf.example всё очень подробно прокоментированно, так что есть смысл дочитать его до конца. Если всё же что-то будет не ясно или не до конца понятно то милости просим в страницы мана:

man smb.conf

После того, как файл настроен необходимо его сохранить в вашем любимом редакторе и запустить сервер самбы:

/etc/init.d/samba start


Кстати заметте, что при перезапуске сервера через консоль, он автоматически в дополнение к демону smbd перезапускает в качестве зависимости и демон nmbd

Далее добавляем сервер в автозагрузку:

rc-update add samba default

Рассматривать весь файл конфигурации я не буду, а раскажу, как можно настроить сервер на работу в обычной домашней локальной сети для удобной организации файловой "свалки" с возможность полного доступа к ней всех членов домашней сети, включая выполнение файлов (к примеру удобно воспроизводить видео не скачивая как требует того протокол FTP)

Настройка на полный доступ для домашней сети

Приведу пример конфига уже с моими коментариями прямо в нём:

File: /etc/samba/smb.conf
#======================= Global Settings =====================================
[global]

# workgroup = NT-Domain-Name or Workgroup-Name, eg: MIDEARTH
   workgroup = FRC

# server string is the equivalent of the NT Description field
   server string = Donik Samba Server

# Server role. Defines in which mode Samba will operate.
   server role = standalone server

# Restrict connections to machines which are on your local network.
   hosts allow = 192.168.0. 10.8.0.
   hosts deny = 0.0.0.0/0

#---------------------------------------------------------------
#       !!!READ INFO FOR "bind interfaces only" OPTION!!!       |
#---------------------------------------------------------------
# if you have
#
# bind interfaces only = yes
#       - it would not listen to non-broadcast interfaces (which openvpn tun0 is). This is written in man smb.conf:
#
#               Note that you should not use this parameter for machines that are serving PPP or other intermittent
#               or non-broadcast network interfaces as it will not cope with non-permanent interfaces.


# If you have multiple network interfaces then you must list them here.
#   interfaces = 192.168.0.0/24
   interfaces = enp3s0 tun0
# To bind all Samba services to the Interfaces list above
   bind interfaces only = no

# this tells Samba to use a separate log file for each machine
   log file = /var/log/samba/log.%m

# Put a capping on the size of the log files (in Kb).
   max log size = 10000

# Level of logging 0-10. 0 is none, 3 is considerable. 1 is the default
  log level = 2


# Determine the security mode. Others are: ads and domain
  security = User

# what to do with user login requests that don.t match a valid UNIX user in some way.
# Never . Means user login requests with an invalid password are rejected.
  map to guest = Never

# This sets the NetBIOS name by which a Samba server is known.
  netbios name = Donik

# DNS Proxy - tells Samba whether or not to try to resolve NetBIOS names via DNS nslookups
   dns proxy = no

#Get rid of error
# "nmbd: Error - should be sent to WINS server"
os level = 255
wins support = Yes

# These scripts are used on a domain controller or stand-alone
# machine to add or delete corresponding unix accounts
;  add user script = /usr/sbin/useradd %u
;  add group script = /usr/sbin/groupadd %g
;  add machine script = /usr/sbin/adduser -n -g machines -c Machine -d /dev/null -s /bin/false %u
;  delete user script = /usr/sbin/userdel %u
;  delete user from group script = /usr/sbin/deluser %u %g
;  delete group script = /usr/sbin/groupdel %g


#============================ Share Definitions ==============================

[warez]
        comment = Private files
        path = /mnt/samba
        read only = No
        valid users = samba
        create mask = 0640
        directory mask = 0750
        guest ok = no

#[temp]
#       comment = Temp files
#       path = /mnt/samba/ochakovo/temp
#       read only = No
#       valid users = samba
#       create mask = 0600
#       directory mask = 0700
#       guest ok = no

#[torrent]
#       comment = Torrents downloading dir
#       path = /mnt/samba/ochakovo/torrents
#       read only = No
#       valid users = samba
#       create mask = 0660
#       directory mask = 0770
#       force group = users
#       guest ok = no

#[pub]
#       comment = Public FTP
#       path = /home/ftp/pub
#       read only = No
#       valid users = samba
#       create mask = 0644
#       directory mask = 0755
#       guest ok = no

И самое главное не забыть дать нужные права к папкам с шарами (учитывая группы и пользователей, а так же тот факт, что не все могут и должны читать и писать). Напрмер, вот такие права можно дать:

chmod 750 /path/to/share/samba

Добавляем польователя шары

Самба использует юзеров реально существующих в системе (файл /etc/passwd ), но при этом они должны быть занесены в собственную БД юезров самбы.

Поэтому создаём пользователя в ОС, но без права залогинится и использовать шел:

useradd -g primgrp -s /sbin/nologin -G secgrp samba

Тут создаётся пользователь с именем samba с первчиной (основной) группой primgrp и допольнительной группой secgrp

Например:

useradd -g warez -s /sbin/nologin -d /mnt/samba samba

Далее даём ему любой сложности рандомный пароль, запоминать который не нужно. Чем сложнее тем лучше =)

passwd samba

Теперь добавляем в БД самбы нового юзера и попутно задаём ему тот пароль, который будет он использовать при подключении сетевого диска.

Note: Этот пароль может совершенно быть другим и рекомендуется его использовать совершенно другим!
pdbedit -a -u samba

После чего рестартим самбу.

Чтобы всё работало как требуется, главное проследить права, которые мы имеем у пользователя и его групп на файлы и папки той директории, которую мы шарим через самбу.

Ссылки

  1. HOWTO Samba в Gentoo
  2. pdbedit]