Передача файлов по сети linux
Содержание:
PARAMETERS
Parameters define the specific attributes of sections.
Some parameters are specific to the section (e.g., security). Some parameters
are usable in all sections (e.g., create mask). All others are permissible only in normal
sections. For the purposes of the following descriptions the and sections will be
considered normal. The letter G in parentheses indicates that a parameter is specific to
the section. The letter S indicates that a parameter can be specified in a
service specific section. All S parameters can also be specified in the section
— in which case they will define the default behavior for all services.
Шаг 6. Подготовка конфигурационных файлов smbldap-tools
Сертификаты, сформированные для LDAP-TLS временно используем и для smbldap-tools. Для этого из папки /etc/ssl/servercerts файлы servercert.pem и serverkey.pem копируем в /etc/smbldap-tools. Попытки использовать указанные server*.pem из общего каталога совместно smbldap-tools и slapd к успеху не привели, поэтому и используются те же сертификаты, но для smbldap-tools они будут использоваться из отдельного каталога.
Получим SID домена:
– вернет SID домена
Используем файл configure.pl. Для этого его из /usr/share/doc/packages/smbldap-tools копируем в /usr/sbin — и запускаем. На консоль будут выводиться вопросы и в большинстве пунктов значение параметра по умолчанию — если мы согласны с этим значением, то просто нажимаем «Enter». В результате сформируются конфигурационные файлы в каталоге /etc/smbldap-tools. Проверяем текст smbldap.conf и smbldap_bind.conf, при этом:
- SID домена должен соответствовать выводу команды net getlocalsid
- Slave и Master LDAP server — это один и тот же наш сервер, его IP- адрес 127.0.0.1
#Настройки шаблонов – например, простейшие:
userSmbHome=»».»»
userProfile=»».»»
userHomeDrive=»»»
userScript=»»
И последнее – в файле smbldap-bind.conf будет текущий пароль администратора каталога для ведомого и ведущего сервера, и так как у нас это один и тот же сервер – то и повторится он дважды, в формате plain-text.
Теперь используя YaST нужно создать Posix-группы для домена, с корректировкой GID — ntadmins gid=512, mashines gid=515, ntguests gid=514, ntusers gid=513.
Примечание: posix-группы «nt*» и «mashines» будут «привязываться» (mapping) к созданным в каталоге LDAP объектам домена. Известно, что у Windows – группы имеется SID (идентификатор Microsoft), этот SID в целях эмуляции контроллера Windows “привязывается” к posix-группе командой net groupmap add. При определении gid posix-группам со значением по умолчанию у меня как раз и не получалось исполнить этот mapping – пока не вписал posix gid равным последним трем цифрам windows- классификатора, как и указано выше, в результате привязка упростилась.
Основы взаимодействия Windows и Linux (протоколы и другие особенности)
В Linux для организации доступа к удаленной системе достаточно знать лишь IP адрес. Вместе с системой DNS, IP адресация представляет собой вполне законченный механизм взаимодействия между системами Linux. В Windows сложилась другая ситуация. Изначально, сети Windows находились в совершенно другом пространстве имен, это было следствием попытки организовать взаимодействие без участия протокола TCP/IP. Для чего был разработан родной для Windows протокол NetBEUI (Network Basic Extended Interface — основной расширенный сетевой пользовательский интерфейс). Не углубляясь в принципы сетевого взаимодействия можно сказать, что NetBEUI состоит из протокола SMB, транспортируемого по протоколу NetBIOS и обернутого в адресуемый протокол LLC, который является подуровнем канального уpовня. Из сказанной каши можно с трудом понять, что NetBEUI не принадлежит какому-либо из уровней . В итоге, данный протокол получился не маршрутизируемым и малоэффективным.Через некоторое время, на основе NetBEUI был разработан протокол NetBIOS Frame (NBF) protocol (NetBIOS over IEEE 802.2 LLC). Следующим шагом была реализация NBT (NetBIOS over TCP/IP).
Протокол NetBIOS (точнее SMB) обладает своим собственным пространством имен. Все имена могут иметь длину до 16 алфавитно-цифровых символов. При этом, использовать имена, начинающиеся с цифры не приемлемо для реализации протокола NetBIOS over TCP/IP, т.к. данное имя будет интерпретироваться как IP-адрес. В NetBIOS существует понятие Рабочая группа (в последствии замененное понятием домен). Компьютеры, имеющие одинаковое имя рабочей группы принадлежат одной группе.
NetBIOS over TCP/IP использует два основных протокола и два порта 139/tcp (порт службы сеанса NetBIOS) и 137/udp (порт сервера имен NetBIOS). Порт UDP используется для разрешения имен на основе широковещательных рассылок, что в большой сети порождает большой трафик. Чтобы уменьшить большой широковещательный трафик, необходимо использовать сервер имен NetBIOS (в Microsoft данный сервер получил название WINS — Windows Internet Naming Service). WINS для NetBIOS over TCP/IP это как DNS для TCP/IP.
С появлением Win2k и Active Directory, Microsoft полностью отказалась от NetBIOS. Вместо NetBIOS стал использоваться SMB через TCP/IP (без использования протокола NetBIOS, его же называют NetBIOS-less). Данный протокол позволял отказаться от WINS и резолвить имена с помощью DNS, используя связку системы безопасности Kerberos и службу каталогов Active Directory. Active Directory — это LDAP каталог (аналог OpenLDAP), которому я обязательно посвящу статью.
Чтобы SAMBA работала без поддкржки NetBIOS, необходимо, чтобы система была членом домена Active Directory!!! Если система НЕ член домена, то отключать поддержку NetBIOS не стоит!
Собственно, протокол SMB и дал начало названия проекта Samba. Через некоторое время SMB был переименован в CIFS (Common Internet File System). Samba версии 2 может использоваться только совместно с протоколом NetBT (NetBIOS over TCP/IP). Версия Samba 3 способна обеспечивать совместимость по протоколу SMB через TCP/IP (NetBIOS-less TCP/IP) и совместима с Active Directory. При использовании SMB через TCP/IP используется порт 445/tcp, а так же 135/tcp для обеспечения взаимодействия по протоколу DCE RPC (удаленные вызовы процедур).
При установке и настройке Samba (без членства в домене Active Directory) желательно использовать демон Samba как сервер WINS или как член сервера WINS для снижения нагрузки мультикаст трафика в сети.
SPECIAL SECTIONS
The section
Parameters in this section apply to the server as a whole, or are defaults for sections that do not
specifically define certain items. See the notes under PARAMETERS for more information.
The section
If a section called is included in the configuration file, services connecting clients
to their home directories can be created on the fly by the server.
When the connection request is made, the existing sections are scanned. If a match is found, it is
used. If no match is found, the requested section name is treated as a username and looked up in the local
password file. If the name exists and the correct password has been given, a share is created by cloning the
section.
Some modifications are then made to the newly created share:
-
The share name is changed from homes to the located username.
-
If no path was given, the path is set to the user’s home directory.
If you decide to use a path = line in your section, it may be useful
to use the %S macro. For example:
is useful if you have different home directories for your PCs than for UNIX access.
This is a fast and simple way to give a large number of clients access to their home directories with a minimum
of fuss.
A similar process occurs if the requested section name is “homes”, except that the share
name is not changed to that of the requesting user. This method of using the section works well if
different users share a client PC.
The section can specify all the parameters a normal service section can specify, though some make more sense
than others. The following is a typical and suitable section:
An important point is that if guest access is specified in the section, all home directories will be
visible to all clients without a password. In the very unlikely event that this is actually
desirable, it is wise to also specify read only access.
The browseable flag for auto home directories will be inherited from the global browseable
flag, not the browseable flag. This is useful as it means setting browseable = no in
the section will hide the share but make any auto home directories visible.
PARAMETERS
Parameters define the specific attributes of sections.
Some parameters are specific to the section (e.g., security). Some parameters
are usable in all sections (e.g., create mask). All others are permissible only in normal
sections. For the purposes of the following descriptions the and sections will be
considered normal. The letter G in parentheses indicates that a parameter is specific to
the section. The letter S indicates that a parameter can be specified in a
service specific section. All S parameters can also be specified in the section
— in which case they will define the default behavior for all services.
IDENTITY MAPPING CONSIDERATIONS
In the SMB protocol, users, groups, and machines are represented by their security identifiers (SIDs).
On POSIX system Samba processes need to run under corresponding POSIX user identities and
with supplemental POSIX groups to allow access to the files owned by those users and groups.
The process of mapping SIDs to POSIX users and groups is called IDENTITY MAPPING
or, in short, ID MAPPING.
Samba supports multiple ways to map SIDs to POSIX users and groups. The configuration is driven by
the option which allows one to specify identity
mapping (idmap) options for each domain separately.
Identity mapping modules implement different strategies for mapping of SIDs to POSIX user and group
identities. They are applicable to different use cases and scenarios. It is advised to read the documentation
of the individual identity mapping modules before choosing a specific scenario to use. Each identity
management module is documented in a separate manual page. The standard idmap backends are
tdb (idmap_tdb(8)),
tdb2 (idmap_tdb2(8)),
ldap (idmap_ldap(8)),
rid (idmap_rid(8)),
hash (idmap_hash(8)),
autorid (idmap_autorid(8)),
ad (idmap_ad(8)),
nss (idmap_nss(8)), and
rfc2307 (idmap_rfc2307(8)).
Overall, ID mapping configuration should be decided carefully. Changes to the already deployed ID mapping
configuration may create the risk of losing access to the data or disclosing the data to the wrong parties.
This example shows how to configure two domains with idmap_rid(8), the principal domain and a trusted domain,
leaving the default id mapping scheme at tdb.
Если используется winbind
Если SAMBA будет взаимодействовать с доменом, то необходимо будет использовать демон winbindd. Собственно, в статье все настройки для winbind учтены. Что необходимо сделать дополнительно:
- Модифицировать init-скрипт /etc/init.d/winbind. Этот скрипт абсолютно идентичен /etc/init.d/samba и содержит те же недостатки и переделывается аналогично.
- При настройке сети необходимо учесть нюансы настроек файлов /etc/nsswitch.conf и других, указанных в статье SAMBA как член домена AD.
Резюме
На этом можно считать HOWTO завершенной. По аналогии, можно запустить демонов хоть на 3,4…20 сетевых интерфейсов, создав соответствующие файлы smb.conf и init скрипты. При обновлении SAMBA наши конфиги не должны пострадать. Но все же стоит после обновления проконтролировать, не заменился ли /etc/init.d/samba на оригинальный. Так же, при настройке данной схемы, я предпочитаю удалять оригинальные каталоги /var/log/samba, /var/run/samba и /var/cache/samba, чтобы не возникало путаницы. Буду рад вашим комментариям и дополнениям! Удачных внедрений!
FILE FORMAT
The file consists of sections and parameters. A section begins with the name of the section in square brackets
and continues until the next section begins. Sections contain parameters of the form:
=
The file is line-based — that is, each newline-terminated line represents either a comment, a section name or
a parameter.
Section and parameter names are not case sensitive.
Only the first equals sign in a parameter is significant. Whitespace before or after the first equals sign is
discarded. Leading, trailing and internal whitespace in section and parameter names is irrelevant. Leading
and trailing whitespace in a parameter value is discarded. Internal whitespace within a parameter value is
retained verbatim.
Any line beginning with a semicolon (“;”) or a hash (“#”)
character is ignored, as are lines containing only whitespace.
Any line ending in a “” is continued on the next line in the customary UNIX fashion.
Настройка ротации логов SAMBA
О syslog и logrotate я писал в прошлых статьях. Этих знаний должно быть вполне достаточно, чтобы понять следующий конфиг:
root@debian:~# # оригинальный конфиг:
root@debian:~# vim /etc/logrotate.d/samba
/var/log/samba/log.smbd {
weekly
missingok
rotate 7
postrotate
/etc/init.d/samba reload > /dev/null
endscript
compress
notifempty
}
/var/log/samba/log.nmbd {
weekly
missingok
rotate 7
postrotate
[ ! -f /var/run/samba/nmbd.pid ] || kill -HUP `cat /var/run/samba/nmbd.pid`
endscript
compress
notifempty
}
root@debian:~# # переделанный для нескольких интерфейсов:
root@debian:~# vim /etc/logrotate.d/samba
## в целом, конфиг необходимо формировать по следующим правилам:
#/путь/к/логам/log.* {
## путь задается в том формате, который задан в параметре log file
# weekly
# missingok
# rotate 7
# postrotate
## пути к pid указываются в соответствии с параметром pid directory
# [ ! -f /путь/к/pid/файлу_nmbd.pid ] || /bin/kill -HUP `cat /путь/к/pid/файлу_nmbd.pid`
# [ ! -f /путь/к/pid/файлу_smbd.pid ] || /bin/kill -HUP `cat //путь/к/pid/файлу_smbd.pid`
## путь к pid'у демона winbind указывать необязательно, если он не используется
# [ ! -f /путь/к/pid/файлу_winbindd.pid ] || /bin/kill -HUP `cat /путь/к/pid/файлу_winbindd.pid`
# endscript
# compress
# notifempty
#}
/var/log/samba-files/log.* {
weekly
missingok
rotate 7
postrotate
[ ! -f /var/run/samba-files/nmbd-smb-files.conf.pid ] || /bin/kill -HUP `cat /var/run/samba-files/nmbd-smb-files.conf.pid`
[ ! -f /var/run/samba-files/smbd-smb-files.conf.pid ] || /bin/kill -HUP `cat /var/run/samba-files/smbd-smb-files.conf.pid`
[ ! -f /var/run/samba-files/winbindd-smb-files.conf.pid ] || /bin/kill -HUP `cat /var/run/samba-files/winbindd-smb-files.conf.pid`
endscript
compress
notifempty
}
/var/log/samba-server/log.* {
weekly
missingok
rotate 7
postrotate
[ ! -f /var/run/samba-server/nmbd-smb-server.conf.pid ] || /bin/kill -HUP `cat /var/run/samba-server/nmbd-smb-server.conf.pid`
[ ! -f /var/run/samba-server/smbd-smb-server.conf.pid ] || /bin/kill -HUP `cat /var/run/samba-server/smbd-smb-server.conf.pid`
[ ! -f /var/run/samba-server/winbindd-smb-server.conf.pid ] || /bin/kill -HUP `cat /var/run/samba-server/winbindd-smb-server.conf.pid`
endscript
compress
notifempty
}
Из данных конфигурационных файлов может возникнуть вопрос, почему pid’ы указаны в таком формате. Об этом я расскажу ниже. В остальном, думаю, что понятно, что пути к каталогу логов и pid’ов необходимо поменять на те, которые были созданы на прошлом шаге, а точнее на те, которые вы укажите в соответствующем конфиге smb.conf для заданного экземпляра samba.
Our experts are sharingtheir knowledge with you.
Categories
▼ Server Hardware
► Hard Disk Drives
no subcategories
► HBAs
no subcategories
► Intel
no subcategories
▼ Modular Server
► Modular Server Ethernet Switch
no subcategories
▼ Motherboards
► BIOS Settings
no subcategories
▼ RAID Controllers
► 3ware
no subcategories
▼ Adaptec
► Adaptec SmartRAID
no subcategories
► LSI
no subcategories
▼ Server
► Backplanes
no subcategories
► LES
no subcategories
▼ SSDs
► Intel SSDs
no subcategories
▼ Server Software
▼ Linux
► Debian
no subcategories
► Linux Basics
no subcategories
► Linux Networking
no subcategories
▼ Linux Performance
► Fio
no subcategories
► TKperf
no subcategories
► Linux Software RAID
no subcategories
▼ Linux-Storage
► LVM
no subcategories
► Smartmontools
no subcategories
► Ubuntu
no subcategories
▼ Windows
► Windows Server 2012
no subcategories
► Windows Server 2016
no subcategories
► Windows Server 2019
no subcategories
▼ Storage
► FreeNAS
no subcategories
▼ Virtualization
► Hyper-V
no subcategories
► Proxmox
no subcategories
► VirtualBox
no subcategories
▼ VMware
▼ VMware
▼ VMware
► VMware
► VMware vSphere 5
► VMware vSphere 5.1
► VMware vSphere 5.5
► VMware vSphere 6.0
► VMware vSphere 6.5
► VMware vSphere 6.7
► VMware vSphere 5
no subcategories
► VMware vSphere 5.1
no subcategories
► VMware vSphere 5.5
no subcategories
► VMware vSphere 6.0
no subcategories
► VMware vSphere 6.5
no subcategories
► VMware vSphere 6.7
no subcategories
► VMware vSphere 5
no subcategories
► VMware vSphere 5.1
no subcategories
► VMware vSphere 5.5
no subcategories
► VMware vSphere 6.0
no subcategories
► VMware vSphere 6.5
no subcategories
► VMware vSphere 6.7
no subcategories
▼ Focus Topics
► Git
no subcategories
► UEFI
no subcategories
▼ Network+Accessories
► Load Balancer
no subcategories
► Monitoring
no subcategories
▼ OPNsense
► OPNsense Business Edition
no subcategories
▼ Remote Management
► IPMI
no subcategories
► TKmon
no subcategories
▼ Archive
► AMD
no subcategories
► Areca
no subcategories
► Fusion-io
no subcategories
► News
no subcategories
► Server Hardware Archive
no subcategories
► STEC
no subcategories