Samba logs in linux

Samba logs in linux

Occasionally, we need to find out what Samba is up to. This is especially true when Samba is performing an unexpected action or is not performing at all. To find out this information, we need to check Samba’s log files to see exactly why it did what it did.

Samba log files can be as brief or verbose as you like. Here is an example of what a Samba log file looks like:

[1999/07/21 13:23:25, 3] smbd/service.c:close_cnum(514) phoenix (192.168.220.101) closed connection to service IPC$ [1999/07/21 13:23:25, 3] smbd/connection.c:yield_connection(40) Yielding connection to IPC$ [1999/07/21 13:23:25, 3] smbd/process.c:process_smb(615) Transaction 923 of length 49 [1999/07/21 13:23:25, 3] smbd/process.c:switch_message(448) switch message SMBread (pid 467) [1999/07/21 13:23:25, 3] lib/doscalls.c:dos_ChDir(336) dos_ChDir to /home/samba [1999/07/21 13:23:25, 3] smbd/reply.c:reply_read(2199) read fnum=4207 num=2820 nread=2820 [1999/07/21 13:23:25, 3] smbd/process.c:process_smb(615) Transaction 924 of length 55 [1999/07/21 13:23:25, 3] smbd/process.c:switch_message(448) switch message SMBreadbraw (pid 467) [1999/07/21 13:23:25, 3] smbd/reply.c:reply_readbraw(2053) readbraw fnum=4207 start=130820 max=1276 min=0 nread=1276 [1999/07/21 13:23:25, 3] smbd/process.c:process_smb(615) Transaction 925 of length 55 [1999/07/21 13:23:25, 3] smbd/process.c:switch_message(448) switch message SMBreadbraw (pid 467)

Many of these options are of use only to Samba programmers. However, we will go over the meaning of some of these entries in more detail in Chapter 9, Troubleshooting Samba .

Samba contains six options that allow users to describe how and where logging information should be written. Each of these options are global options and cannot appear inside a share definition. Here is an up-to-date configuration file that covers each of the share and logging options that we’ve seen so far:

[global] netbios name = HYDRA server string = Samba %v on (%I) workgroup = SIMPLE # Networking configuration options hosts allow = 192.168.220. 134.213.233. localhost hosts deny = 192.168.220.102 interfaces = 192.168.220.100/255.255.255.0 \ 134.213.233.110/255.255.255.0 bind interfaces only = yes # Debug logging information log level = 2 log file = /var/log/samba.log.%m max log size = 50 debug timestamp = yes [data] path = /home/samba/data browseable = yes guest ok = yes comment = Data Drive volume = Sample-Data-Drive writeable = yes

Here, we’ve added a custom log file that reports information up to debug level 2. This is a relatively light debugging level. The logging level ranges from 1 to 10, where level 1 provides only a small amount of information and level 10 provides a plethora of low-level information. Level 2 will provide us with useful debugging information without wasting disk space on our server. In practice, you should avoid using log levels greater than 3 unless you are programming Samba.

This file is located in the /var/log directory thanks to the log file configuration option. However, we can use variable substitution to create log files specifically for individual users or clients, such as with the %m variable in the following line:

log file = /usr/local/logs/samba.log.%m

Isolating the log messages can be invaluable in tracking down a network error if you know the problem is coming from a specific machine or user.

We’ve added another precaution to the log files: no one log file can exceed 50 kilobytes in size, as specified by the max log size option. If a log file exceeds this size, the contents are moved to a file with the same name but with the suffix .old appended. If the .old file already exists, it is overwritten and its contents are lost. The original file is cleared, waiting to receive new logging information. This prevents the hard drive from being overwhelmed with Samba log files during the life of our daemons.

Читайте также:  What is man command in linux

For convenience, we have decided to leave the debug timestamp in the logs with the debug timestamp option, which is the default behavior. This will place a timestamp next to each message in the logging file. If we were not interested in this information, we could specify no for this option instead.

If you wish to use the system logger ( syslog ) in addition to or in place of the standard Samba logging file, Samba provides options for this as well. However, to use syslog, the first thing you will have to do is make sure that Samba was built with the configure —with-syslog option. See Chapter 2 for more information on configuring and compiling Samba.

Once that is done, you will need to configure your /etc/syslog.conf to accept logging information from Samba. If there is not already a daemon.* entry in the /etc/syslog.conf file, add the following:

This specifies that any logging information from system daemons will be stored in the /var/log/daemon.log file. This is where the Samba information will be stored as well. From there, you can specify the following global option in your configuration file:

This specifies that any logging messages with a level of 1 will be sent to both the syslog and the Samba logging files. (The mappings to syslog priorities are described in the upcoming section «syslog.») Let’s assume that we set the regular log level option above to 4. Any logging messages with a level of 2, 3, or 4 will be sent to the Samba logging files, but not to the syslog. Only level 1 logging messages will be sent to both. If the syslog value exceeds the log level value, nothing will be written to the syslog.

If you want to specify that messages be sent only to syslog — and not to the standard Samba logging files — you can place this option in the configuration file:

If this is the case, any logging information above the number specified in the syslog option will be discarded, just like the log level option.

On our server, Samba outputs log information to text files in the var subdirectory of the Samba home directory, as set by the makefile during the build. The log file option can be used to reset the name of the log file to another location. For example, to reset the name and location of the Samba log file to /usr/local/logs/samba.log, you could use the following:

[global] log file = /usr/local/logs/samba.log

You may use variable substitution to create log files specifically for individual users or clients.

Читайте также:  Linux команда обновления репозиториев

You can override the default log file location using the -l command-line switch when either daemon is started. However, this does not override the log file option. If you do specify this parameter, initial logging information will be sent to the file specified after -l (or the default specified in the Samba makefile) until the daemons have processed the smb.conf file and know to redirect it to a new log file.

The log level option sets the amount of data to be logged. Normally this is left at 0 or 1. However, if you have a specific problem you may want to set it at 3, which provides the most useful debugging information you would need to track down a problem. Levels above 3 provide information that’s primarily for the developers to use for chasing internal bugs, and slows down the server considerably. Therefore, we recommend that you avoid setting this option to anything above 3.

[global] log file = /usr/local/logs/samba.log.%m log level = 3

The max log size option sets the maximum size, in kilobytes, of the debugging log file that Samba keeps. When the log file exceeds this size, the current log file is renamed to add an .old extension (erasing any previous file with that name) and a new debugging log file is started with the original name. For example:

[global] log file = /usr/local/logs/samba.log.%m max log size = 1000

Here, if the size of any log file exceeds one megabyte in size, Samba renames the log file samba.log. machine-name .old and a new log file is generated. If there was a file there previously with the .old extension, Samba deletes it. We highly recommend setting this option in your configuration files because debug logging (even at lower levels) can covertly eat away at your available disk space. Using this option protects unwary administrators from suddenly discovering that most of their disk space has been swallowed up by a single Samba log file.

If you happen to be debugging a network problem and you find that the date-stamp and timestamp information within the Samba log lines gets in the way, you can turn it off by giving either the timestamp logs or the debug timestamp option (they’re synonymous) a value of no . For example, a regular Samba log file presents its output in the following form:

12/31/98 12:03:34 hydra (192.168.220.101) connect to server network as user davecb

With a no value for this option, the output would appear without the datestamp or the timestamp:

hydra (192.168.220.101) connect to server network as user davecb

The syslog option causes Samba log messages to be sent to the Unix system logger. The type of log information to be sent is specified as the parameter for this argument. Like the log level option, it can be a number from 0 to 10. Logging information with a level less than the number specified will be sent to the system logger. However, debug logs equal to or above the syslog level, but less than log level, will still be sent to the standard Samba log files. To get around this, use the syslog only option. For example:

[global] log level = 3 syslog = 1

The syslog only option tells Samba not to use the regular logging files — the system logger only. To enable this, specify the following option in the global ection of the Samba configuration file:

Читайте также:  Создать vpn сервер linux

© 2001, O’Reilly & Associates, Inc.

Источник

Логирование действий на файловом сервере в Samba 4.5

Для логирования/аудита действий пользователей на файловом сервере предусмотрен модуль VFS (Virtual File System) — full_audit, рассмотрим его применение.

В файле конфигурации samba (/etc/samba/smb.conf) в секцию [global] добавим следующие параметры:

# ПАРАМЕНТЫ ЛОГИРОВАНИЯ log level = 0 vfs:1 # ПОДКЛЮЧЕНИЕ МОДУЛЕЙ VFS (Virtual File System) vfs objects = full_audit # АУДИТ СЕТЕВЫХ ПАПОК full_audit:prefix = %S|%u|%I full_audit:success = mkdir rmdir pwrite rename unlink full_audit:failure = none full_audit:facility = local5 full_audit:priority = notice

full_audit:prefix — Запись сообщений в системный журнал с префиксом: %S — название шары, %u — имя пользователя, %I — ip-адрес пользователя.
full_audit:success/full_audit:failure — Фиксирование удачных/неудачных событий (создание, удаление каталога, запись файла, переименование, удаление). Полный список возможных команд
full_audit:facility/full_audit:priority — Параметры системного журнала (syslog), с помощью которых мы идентифицируем наши сообщения от samba

Если уже используется какой-то модуль VFS, то перечисляем все объекты через пробел, например:
vfs object = acl_xattr full_audit

Если необходимо вести логирование пользовательский действий по какой то определенной общей папке, то тогда выше описанные параметры необходимо прописывать в секцию описания общей папки.

После изменения конфигурации, перезапускаем samba, командой:

По-умолчанию логирование записывается в файлы rsyslog и messages и выглядит это следующим образом:

Jan 17 16:14:45 datastore1 smbd_audit: DISK_Z|user1|10.10.16.31|pwrite|ok|test.doc Jan 17 16:14:04 datastore1 smbd_audit: DISK_Z|user1|10.10.10.21|unlink|ok|test.doc Jan 17 16:14:04 datastore1 smbd_audit: DISK_Z|user1|10.10.10.21|mkdir|ok|Новая папка Jan 17 16:14:04 datastore1 smbd_audit: DISK_Z|user1|10.10.10.21|rename|ok|./Новая папка|./Новая папка 2 Jan 17 16:14:04 datastore1 smbd_audit: DISK_Z|user1|10.10.10.21|rmdir|ok|Новая папка 2

Для удобства настроим запись логов в отдельный файл и настроим для этого файла ротацию. Сперва запретим логирование в файлы rsyslog и messages, в файле конфигурации rsyslog (/etc/rsyslog.conf) приводим к виду строки:

*.*;local5,auth,authpriv.none -/var/log/syslog *.=info;*.=notice;*.=warn;\ local5,auth,authpriv.none;\ cron,daemon.none;\ mail,news.none -/var/log/messages

Теперь укажем в какой файл необходимо записывать события. В конец файла добавляем следующую строку:

local5.notice -/var/log/samba/audit_shares.log

ЗАМЕТКА. Знак минуса перед указанием файла означает, что после каждой записи в файл не будет выполняться операция sync, а данные некоторое время будут находится в оперативной памяти в дисковом буфере. При большой интенсивности потока записей это уменьшает нагрузку на дисковую систему.

Для применения изменений перезапускаем rsyslog, командой:

Последний штрих, это настройка ротации для лог-файла. В файл (/etc/logrotate.d/samba) добавляем строки:

/var/log/samba/audit_shares.log < daily rotate 60 missingok compress notifempty olddir /var/log/samba/audit_old >

ПОЯСНЕНИЯ. Используемые параметры указывают что ротацию необходимо делать каждый день (daily), хранить файлы не более 60 дней (rotate), не выдавать ошибок в случае если лог-файла не существует (missingok), не обрабатывать пустые файлы (notifempty) и перемещать старые лог-файлы в отдельную папку (olddir)

ПОНРАВИЛАСЬ ИЛИ ОКАЗАЛАСЬ ПОЛЕЗНОЙ СТАТЬЯ, ПОБЛАГОДАРИ АВТОРА

ПОНРАВИЛАСЬ ИЛИ ОКАЗАЛАСЬ ПОЛЕЗНОЙ СТАТЬЯ, ПОБЛАГОДАРИ АВТОРА

Источник

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