Windows 8 Windows 8 Enterprise Windows 8 Pro Windows Server 2012 Datacenter Windows Server 2012 Datacenter Windows Server 2012 Essentials Windows Server 2012 Foundation Windows Server 2012 Foundation Windows Server 2012 Standard Windows Server 2012 Standard Еще…Меньше
Обзор
Когда разработчик или приложение из-за ошибки конфигурации или разрешение Нет доступа к удаленной общей папке в Windows Server 2012 и Windows 8, данные журнала событий, создаваемые может оказаться достаточно информативным, чтобы быть полезным. Например может появиться следующее сообщение об ошибке при попытке получить доступ к удаленной общей папке в Windows 8 и Windows Server 2012:
Не удается получить доступ к удаленной общей папки
Это может усложнить устранении неполадок внешнего хранилища и протокола блока сообщений сервера (SMB). Исправление для Windows Server 2012 и Windows 8, описанное в разделе «Сведения об исправлении» представляет более надежные ведение журнала событий для SMB.
Решение
Чтобы устранить эту проблему, установите накопительный пакет обновления 2984005 или установить исправление, описанное в разделе «Сведения об исправлении».
Сведения об обновлении
Дополнительные сведения о том, как получить этот накопительный пакет обновления, щелкните следующий номер статьи базы знаний Майкрософт:
2984005 сентября 2014 накопительный пакет обновления для Windows Server 2012, Windows 8 и Windows RT
Сведения об исправлении
Доступно исправление от службы поддержки Майкрософт. Однако данное исправление предназначено для устранения только проблемы, описанной в этой статье. Применяйте это исправление только в тех случаях, когда наблюдается проблема, описанная в данной статье. Это исправление может проходить дополнительное тестирование. Таким образом если вы не подвержены серьезно этой проблеме, рекомендуется дождаться следующего пакета обновления, содержащего это исправление.
Если исправление доступно для скачивания, имеется раздел «Пакет исправлений доступен для скачивания» в верхней части этой статьи базы знаний. Если этот раздел не отображается, обратитесь в службу поддержки для получения исправления.
Примечание. Если наблюдаются другие проблемы или необходимо устранить неполадки, вам может понадобиться создать отдельный запрос на обслуживание. Стандартная оплата за поддержку будет взиматься только за дополнительные вопросы и проблемы, которые не соответствуют требованиям конкретного исправления. Чтобы просмотреть полный список телефонов поддержки и обслуживания клиентов корпорации Майкрософт или создать отдельный запрос на обслуживание, посетите следующий веб-сайт корпорации Майкрософт:
http://support.microsoft.com/contactus/?ws=supportПримечание. В форме «Пакет исправлений доступен для скачивания» отображаются языки, для которых доступно исправление. Если нужный язык не отображается, значит исправление для данного языка отсутствует.
Предварительные условия
Не существует предварительных условий для установки исправления.
Необходимость перезагрузки
После установки исправления компьютер необходимо перезагрузить.
Сведения о замене исправлений
Это исправление не заменяет все ранее выпущенные исправления.
Сведения о файлах
Список файлов, входящих в данное обновление Загрузите сведения о файле для данного обновления 2980749.
Статус
Корпорация Майкрософт подтверждает, что это проблема продуктов Майкрософт, перечисленных в разделе «Относится к».
Дополнительные сведения
Windows Server 2012 R2 и Windows 8.1 введена более надежной событий с событиями более подробного ведения журнала для SMB и улучшенные инструкции. Обновление для Windows Server 2012 и Windows 8 обеспечивает такие же возможности. Вы найдете новых записей в журнале событий в разделе следующие каналы:
-
Microsoft-Windows-SMBClient/Connectivity
-
Microsoft-Windows-SMBClient/Operational
-
Microsoft-Windows-SMBClient/Security
-
Microsoft-Windows-SMBServer/Connectivity
-
Microsoft-Windows-SMBServer/Operational
-
Microsoft-Windows-SMBServer/Security
Для доступа к этим событиям:
-
Откройте окно просмотра событий и затем разверните узел Журналы приложений и служб.
-
Разверните папку « Microsoft ».
-
Разверните папку Windows .
-
Разверните папку SMBClient или SMBServer и выберите пункт каналы.
Примечание. С использованием нового ведения журнала событий и framework каналов, представленные данным исправлением повлияет на любое пользовательское приложение, зависит от старого механизма ведения журнала событий в SMB.
Ссылки
Дополнительные сведения о терминологии , которую корпорация Майкрософт использует для описания обновлений программного обеспечения.
Нужна дополнительная помощь?
|
Needs Expansion |
Contents
- Introduction
- Target Audience
-
System Logs
- Authorization Log
- Daemon Log
- Debug Log
- Kernel Log
- Kernel Ring Buffer
- System Log
-
Application Logs
- Apache HTTP Server Logs
- CUPS Print System Logs
- Rootkit Hunter Log
- Samba SMB Server Logs
- X11 Server Log
-
Non-Human-Readable Logs
- Login Failures Log
- Last Logins Log
- Login Records Log
-
System Logging Daemon (syslogd)
- Configuration of syslogd
- Echoing Messages to syslogd With Logger
- Log Rotation
-
Essential Commands
- Getting Started
- Editing Files
- Viewing Files
- Viewing the Beginning of Files
- Viewing the End of Files
- Watching a Changing File
- Searching Files
-
Resources
- Local System Resources
- WWW Resources
Introduction
One of the things which makes GNU/Linux a great operating system is that virtually anything and everything happening on and to the system may be logged in some manner. This information is invaluable for using the system in an informed manner, and should be one of the first resources you use to trouble-shoot system and application issues. The logs can tell you almost anything you need to know, as long as you have an idea where to look first.
Your Ubuntu system provides vital information using various system log files. These log files are typically plain ASCII text in a standard log file format, and most of them sit in the traditional system log subdirectory /var/log. Many are generated by the system log daemon, syslogd on behalf of the system and certain applications, while some applications generate their own logs by writing directly to files in /var/log.
This guide talks about how to read and use several of these system log files, how to use and configure the system logging daemon, syslogd, and how log rotation works. See the Resources section for additional information.
Target Audience
This guide will be simple enough to use if you have any experience using the console and editing text files using a text editor. See the end of this document for some essential commands that may help you find your way around these files if you’re relatively new to the command line.
System Logs
System logs deal primarily with the functioning of the Ubuntu system, not necessarily with additional applications added by users. Examples include authorization mechanisms, system daemons, system messages, and the all-encompassing system log itself, syslog.
The Authorization Log tracks usage of authorization systems, the mechanisms for authorizing users which prompt for user passwords, such as the Pluggable Authentication Module (PAM) system, the sudo command, remote logins to sshd and so on. The Authorization Log file may be accessed at /var/log/auth.log. This log is useful for learning about user logins and usage of the sudo command.
Use grep to cut down on the volume. For example, to see only information in the Authorization Log pertaining to sshd logins, use this:
grep sshd /var/log/auth.log | less
Daemon Log
A daemon is a program that runs in the background, generally without human intervention, performing some operation important to the proper running of your system. The daemon log at /var/log/daemon.log and contains information about running system and application daemons such as the Gnome Display Manager daemon gdm, the Bluetooth HCI daemon hcid, or the MySQL database daemon mysqld. This can help you trouble-shoot problems with a particular daemon.
Again, use grep to find specific information, plugging in the name of the daemon you’re interested in.
Debug Log
The debug log at /var/log/debug and provides detailed debug messages from the Ubuntu system and applications which log to syslogd at the DEBUG level.
Kernel Log
The kernel log at /var/log/kern.log provides a detailed log of messages from the Ubuntu Linux kernel. These messages may prove useful for trouble-shooting a new or custom-built kernel, for example.
Kernel Ring Buffer
The kernel ring buffer is not really a log file per se, but rather an area in the running kernel you can query for kernel bootup messages via the dmesg utility. To see the messages, use this:
dmesg | less
Or to search for lines that mention the Plug & Play system, for example, use grep like this:
dmesg | grep pnp | less
By default, the system initialization script /etc/init.d/bootmisc.sh sends all bootup messages to the file /var/log/dmesg as well. You can view and search this file the usual way.
System Log
The system log typically contains the greatest deal of information by default about your Ubuntu system. It is located at /var/log/syslog, and may contain information other logs do not. Consult the System Log when you can’t locate the desired log information in another log. It also contains everything that used to be in /var/log/messages.
Application Logs
Many applications also create logs in /var/log. If you list the contents of your /var/log subdirectory, you will see familiar names, such as /var/log/apache2 representing the logs for the Apache 2 web server, or /var/log/samba, which contains the logs for the Samba server. This section of the guide introduces some specific examples of application logs, and information contained within them.
Apache HTTP Server Logs
The default installation for Apache2 on Ubuntu creates a log subdirectory: /var/log/apache2. Within this subdirectory are two log files with two distinct purposes:
-
/var/log/apache2/access.log — records of every page served and every file loaded by the web server.
-
/var/log/apache2/error.log — records of all error conditions reported by the HTTP server
By default, every time Apache accesses a file or page, the access logs record the IP address, time and date, browser identification string, HTTP result code and the text of the actual query, which will generally be a GET for a page view. Look at the Apache documentation for a complete rundown; quite a lot can be gleaned from this file, and indeed many statistical packages exist that perform analyses of these logs.
Also, every time any error occurs, Apache adds a line to the error log. If you run PHP with error and warning messages disabled, this can be your only way to identify bugs.
CUPS Print System Logs
The Common Unix Printing System (CUPS) uses the default log file /var/log/cups/error_log to store informational and error messages. If you need to solve a printing issue in Ubuntu, this log may be a good place to start.
Rootkit Hunter Log
The Rootkit Hunter utility (rkhunter) checks your Ubuntu system for backdoors, sniffers and rootkits, which are all signs of compromise of your system. The log rkhunter uses is located at /var/log/rkhunter.log.
Samba SMB Server Logs
The Server Message Block Protocol (SMB) server, Samba is popularly used for sharing files between your Ubuntu computer and other computers which support the SMB protocol. Samba keeps three distinct types of logs in the subdirectory /var/log/samba:
-
log.nmbd — messages related to Samba’s NETBIOS over IP functionality (the network stuff)
-
log.smbd — messages related to Samba’s SMB/CIFS functionality (the file and print sharing stuff)
-
log.[IP_ADDRESS] — messages related to requests for services from the IP address contained in the log file name, for example, log.192.168.1.1.
X11 Server Log
The default X11 Windowing Server in use with Ubuntu is the Xorg X11 server, and assuming your computer has only one display defined, it stores log messages in the file /var/log/Xorg.0.log. This log is helpful for diagnosing issues with your X11 environment.
Non-Human-Readable Logs
Some log files found in the /var/log subdirectory are designed to be readable by applications, not necessarily by humans. Some examples of such log files which appear in /var/log follow.
Login Failures Log
The login failures log located at /var/log/faillog is actually designed to be parsed and displayed by the faillog command. For example, to print recent login failures, use this:
faillog
Last Logins Log
The last logins log at /var/log/lastlog should not typically be parsed and examined by humans, but rather should be used in conjunction with the lastlog command. For example to see a listing of logins with the lastlog command, displayed one page per screen with the less command, use the following command:
lastlog | less
Login Records Log
The file /var/log/wtmp contains login records, but unlike /var/log/lastlog above, /var/log/wtmp is not used to show a list of recent logins, but is instead used by other utilities such as the who command to present a listed of currently logged in users. This command will show the users currently logged in to your machine:
who
System Logging Daemon (syslogd)
The system logging daemon syslogd, also known as sysklogd, awaits logging messages from numerous sources and routes the messages to the appropriate file or network destination. Messages logged to syslogd usually contain common elements like system hostnames and time-stamps in addition to the specific log information.
Configuration of syslogd
The syslogd daemon’s configuration file is /etc/syslog.conf. Each entry in this file consists of two fields, the selector and the action. The selector field specifies a facility to be logged, such as for example the auth facility which deals with authorization, and a priority level to log such information at, such as info, or warning. The action field consists of a target for the log information, such as a standard log file (i.e. /var/log/syslog), or the hostname of a remote computer to send the log information to.
Echoing Messages to syslogd With Logger
A neat utility exists in the logger tool, which allows one to place messages into the System Log (i.e. /var/log/syslog) arbitrarily. For example, assume your user name is buddha, and you would like to enter a message into the syslog about a particularly delicious pizza you’re eating, you could use a command such as the following at a terminal prompt:
logger This Pizza from Vinnys Gourmet Rocks
and you would end up with a line in the /var/log/syslog file like this:
Jan 12 23:34:45 localhost buddha: This Pizza from Vinnys Gourmet Rocks
You can even specify a tag the messages come from, and redirect the output standard error too.
# # sample logger error jive # logmsg="/usr/bin/logger -s -t MyScript " # announce what this script is, even to the log $logmsg "Directory Checker FooScript Jive 1.0" # test for the existence of Fred's home dir on this machine if [ -d /home/fred ]; then $logmsg "I. Fred's Home Directory Found" else $logmsg "E. Fred's Home Directory was NOT Found. Boo Hoo." exit 1 fi
Executing this script as chkdir.sh on the machine butters where Fred does not have a home directory, /home/fred, gives the following results:
bumpy@butters:~$./chkdir.sh MyScript: Directory Checker FooScript Jive 1.0 MyScript: E. Fred's Home Directory was NOT Found. Boo Hoo. bumpy@butters:~$tail -n 2 /var/log/syslog Jan 12 23:23:11 localhost MyScript: Directory Checker FooScript Jive 1.0 Jan 12 23:23:11 localhost MyScript: E. Fred's Home Directory was NOT Found. Boo Hoo.
So, as you can see, we received the messages both via standard error, at the terminal prompt, and they also appear in our syslog.
Log Rotation
When viewing directory listings in /var/log or any of its subdirectories, you may encounter log files with names such as daemon.log.0, daemon.log.1.gz, and so on. What are these log files? They are ‘rotated’ log files. That is, they have automatically been renamed after a predefined time-frame, and a new original log started. After even more time the log files are compressed with the gzip utility as in the case of the example daemon.log.1.gz. The purpose of log rotation is to archive and compress old logs so that they consume less disk space, but are still available for inspection as needed. What handles this functionality? Why, the logrotate command of course! Typically, logrotate is called from the system-wide cron script /etc/cron.daily/logrotate, and further defined by the configuration file /etc/logrotate.conf. Individual configuration files can be added into /etc/logrotate.d (where the apache2 and mysql configurations are stored for example).
This guide will not cover the myriad of ways logrotate may be configured to handle the automatic rotation of any log file on your Ubuntu system. For more detail, check the Resources section of this guide.
NOTE: You may also rotate system log files via the cron.daily script /etc/cron.daily/sysklogd instead of using logrotate. Actually, the utility savelog may produce unexpected results on log rotation which configuring logrotate seems to have no effect on. In those cases, you should check the cron.daily sysklogd script in /etc/cron.daily/sysklogd and read the savelog manual page to see if savelog is not in fact doing the rotation in a way that is not what you are specifying with logrotate.
Essential Commands
If you’re new to the console and the Linux command line, these commands will get you up and running to the point where you can work with log files at a basic level.
Getting Started
To change to the log directory, where most of these files sit, use the cd command. This saves having to type out a full path name for every subsequent command:
cd /var/log
Editing Files
You can view and edit files in GEdit or Kate, the simple text editors that come with Ubuntu and Kubuntu respectively, but these can be overkill when all you want to do is look at a file or make simple changes. The easiest editor to use from the console is nano, which is less powerful but also less complicated than vim or emacs. The command to edit a particular logfile /var/log/example.log using nano is:
nano example.log
Press Ctrl+X to exit. It will ask if you want to save your changes when you exit, but unless you run it with the sudo command the files won’t be writable. In general, you won’t want to save your changes to log files, of course.
Viewing Files
To simply look at a file, an editor is overkill. Use the less command, which pages through a file one screen at a time:
less example.log
You don’t need sudo to look at a file. Press h for help, or q to quit. The cursor keys and page up/down keys will work as expected, and the slash key («/») will do a case-sensitive search; the n key repeats the last search.
Viewing the Beginning of Files
To see the first ten lines of a file, use the head command:
head example.log
To see some other number of lines from the beginning of the file, add the -n switch, thus:
head -n 20 example.log
Viewing the End of Files
To see the final ten lines of a file, the analogous command is tail:
tail example.log
Again, the -n switch gives you control over how many lines it displays:
tail -n 20 example.log
Watching a Changing File
Also, the -f («follow») switch puts tail into a loop, constantly waiting for new additions to the file it’s displaying. This is useful for monitoring files that are being updated in real time:
tail -f example.log
Press Ctrl+C to quit the loop.
Searching Files
Because log files can be large and unwieldy, it helps to be able to focus. The grep command helps you strip out only the content you care about. To find all the lines in a file containing the word «system», for example, use this:
grep "system" example.log
To find all the lines containing «system» at the beginning of the line, use this:
grep "^system" example.log
Note the caret symbol, a regular expression that matches only the start of a line. This is less useful for standard log files, which always start with a date and time, but it can be handy otherwise. Not all files have a standard format.
Any time the result of a grep is still too long, you can pipe it through less:
grep "system" example.log | less
Resources
Additional information on system and application logs and syslogd is available via the following resources:
Local System Resources
man dmesg |
System manual page for the dmesg kernel ring buffer utility |
man faillog |
System manual page for the faillog command (and also the faillog configuration file via man 5 faillog) |
man grep |
System manual page for the grep pattern searching utility |
man head |
System manual page for the head utility |
man klogd |
System manual page for the kernel log daemon (klogd) |
man last |
System manual for the last command which shows last logged in users |
man less |
System manual page for the less paging utility |
man logger |
System manual page for the logger command-line interface to syslog utility |
man logrotate |
System manual page for the the logrotate utility |
man savelog |
System manual page for the savelog log file saving utility |
man syslogd |
System manual page for the system log daemon (syslogd) |
man syslog.conf |
System manual page for the syslogd configuration file |
man tail |
System manual page for the tail utility |
WWW Resources
Checking Your System Logs with awk
Syslog — Watching Your Logs
http://www.ibm.com/developerworks/linux/library/l-roadmap5/-Linux Logging
Sawing Linux Logs With Simple Tools
CategorySystem
Настройка протоколирования событий, связанных с файловым хранилищем samba, является довольно важным вопросом. Рассмотрим случай, когда на файловом сервере присутствуют сетевые папки, для которых необходимо организовать запись действий, которые пользователи производят в данной папке.
За настройку журналирования действий samba отвечает конфигурационный файл /etc/samba/smb.conf.
Рассмотрим пример сетевой папки, имеющей в своем теле конфигурацию для протоколирования событий.
Секция сетевой папки:
[share_domain] path = /share_domain/ read only = no browseable = yes vfs objects = full_audit full_audit:prefix = %u|%I|%m|%S full_audit:failure = none full_audit:success = mkdir rmdir open read pread write pwrite sendfile rename unlink lock full_audit:facility = local5 full_audit:priority = debug
Рассмотрим детально, что означают данные параметры:
В параметре vfs objects указывается модуль full_audit, на основе которого будет происходить протоколирование событий.
Запись full_audit:prefix = %u|%I|%m|%S представляет из себя набор тех данных, которые будут записываться в логи при определенных действиях пользователей в сетевой папке.
Полный список допустимых переменных
%U — имя пользователя.
%G — имя основной группы %U.
%h — сетевое имя ПК, на котором запущена Samba.
%L — NetBIOS имя сервера.
%M — сетевое имя ПК клиентской машины.
%R — выбранный уровень протокола. Он может быть одним из CORE, COREPLUS, LANMAN1, LANMAN2, NT1, SMB2_02, SMB2_10, SMB3_00, SMB3_02, SMB3_11 или SMB2_FF.
%d — идентификатор текущего серверного процесса.
%a — архитектура удаленной машины.
%I — IP-адрес клиентской машины.
%J — IP-адрес клиентской машины, двоеточия / точки заменены символами подчеркивания.
%i — локальный IP-адрес, к которому подключился клиент.
%j — локальный IP-адрес, к которому подключился клиент, двоеточия / точки заменены символами подчеркивания.
%T — текущие дата и время.
%t — текущие дата и время в минимальном формате без двоеточий (YYYYYmmdd_HHMMSS).
%D — имя домена или рабочей группы текущего пользователя.
%w — разделитель в winbind.
%$(envvar) — значение переменной envar.
Следующие параметры доступны, когда установка соединения состоялась:
%S — название текущей службы, если таковая имеется.
%P — корневой каталог текущей службы, если таковой имеется.
%u — имя пользователя текущего сервиса, если есть.
%g — имя основной группы %u.
%H — домашний каталог пользователя, заданного %u.
%N — Это значение совпадает с %L.
Параметры:
full_audit:failure = none
full_audit:success = mkdir rmdir open read pread write pwrite sendfile rename unlink lock
отвечают за протоколирование действий в случае успешного выполнения операции или неуспешного. Допустимо использование none — т.е. отсутствие протоколирования событий или команд.
Полный список допустимых команд
aio_force
audit_file
brl_lock_windows
brl_unlock_windows
chdir
chflags
chmod
close
closedir
connect
connectpath
create_dfs_pathat
create_file
disconnect
disk_free
durable_cookie
durable_disconnect
durable_reconnect
fallocate
fchmod
fchown
fdopendir
fget_compression
fget_dos_attributes
fget_nt_acl_at
fgetxattr
file_id_create
flistxattr
fremovexattr
fs_capabilities
fsctl
fset_dos_attributes
fset_nt_acl
fsetxattr
fs_file_id
fstat
fsync
fsync_recv
fsync_send
ftruncate
get_alloc_size
get_dfs_referrals
get_dos_attributes
get_dos_attributes_recv
get_dos_attributes_send
getlock
get_nt_acl
get_quota
get_real_filename
get_shadow_copy_data
getwd
getxattr
getxattrat_recv
getxattrat_send
is_offline
kernel_flock
lchown
linkat
linux_setlease
listxattr
lock
lseek
lstat
mkdirat
mknodat
ntimes
offload_read_recv
offload_read_send
offload_write_recv
offload_write_send
open
pread
pread_recv
pread_send
pwrite
pwrite_recv
pwrite_send
read
readdir
readdir_attr
readlinkat
realpath
recvfile
removexattr
renameat
rewinddir
seekdir
sendfile
set_compression
set_dos_attributes
set_offline
set_quota
setxattr
snap_check_path
snap_create
snap_delete
stat
statvfs
streaminfo
strict_lock_check
symlinkat
sys_acl_blob_get_fd
sys_acl_blob_get_file
sys_acl_get_fd
sys_acl_get_file
sys_acl_set_fd
telldir
translate_name
unlinkat
write
Параметры:
full_audit:facility = local5 — категория событий syslog, в которую будут попадать записи.
Для того чтобы каждая сетевая папка вела свои собственные логи, требуется указывать отличные друг от друга значения, т.е. local5, local6, local7 и т.д.
full_audit:priority = debug — категория событий syslog, в которую будут попадать записи.
Доступные приоритеты: notice, debug, alert
Необходимо помнить, для того чтобы настройки вступили в силу, требуется перезапустить сервис:
sudo -E systemctl restart smb
Настройка ведения логов в определенный файл
За пути логов отвечает конфигурационный файл /etc/rsyslog.conf, в конец файла вписывается для каждой сетевой папки свой параметр local4, local5, local6 и т.д.:
local5.debug -/var/log/samba/audit.log
Вместо debug необходимо указать тот режим, который был указан в параметре full_audit:priority.
Также для удобства ведения логов можно назвать файл логов идентично имени сетевой папки, т.е.:
local5.debug -/var/log/samba/share_dir.log
Для применения изменений потребуется перезапустить сервис командой:
sudo -E systemctl restart rsyslog
Настройка ротации логов
За ротации логов отвечает конфигурационный файл /etc/logrotate.d/samba.
По умолчанию в системе уже настроена ротация логов Samba и конфигурационный файл имеет следующее содержимое:
/var/log/samba/log.* { compress dateext maxage 365 rotate 99 notifempty olddir /var/log/samba/old missingok copytruncate }
Рассмотрим, за что отвечают параметры:
-
compress — сжатие данных;
-
dateext — добавляет дату ротации перед заголовком старого лога;
-
maxage — значение, отвечающее за удаление логов старше X дней;
-
rotate — параметр отвечает за частоту ротаций логов через X дней;
-
notifyempty — не сдвигать журнал, если он пуст;
-
olddir /var/log/samba/old — параметр отвечающий, куда сохранять старые логи;
-
missingok — в случае отсутствия файла журнала перейти к обработке следующего, не выдавая сообщения об ошибке;
-
copytruncate — после создания копии обрезать исходный файл журнала взамен перемещения старого файла журнала и создания нового. Данный параметр применяется в том случае, когда некоторой программе нельзя указать закрыть её журнал, и таким образом можно постоянно продолжать запись (добавление) в существующий файл журнала.
Запустить ротацию логов можно следующей командой:
sudo -E logrotate -v -f /etc/logrotate.conf
Если вы нашли ошибку, пожалуйста, выделите текст и нажмите Ctrl+Enter.
The Tool Box
Sometimes Unix
seems to be made up of a grab bag of applications and tools. There
are tools to troubleshoot tools. And of course, there are several
ways to accomplish the same task. When trying to solve a problem
related to Samba, a good plan of attack is to use the following:
-
Samba logs
-
Samba test utilities
-
Unix utilities
-
Fault tree
-
Documentation and FAQs
-
Samba newsgroups
-
Searchable mailing list archives
Let’s go over each of these one-by-one in the
following sections.
Samba Logs
Your first line of attack should always
be to check the log files. The Samba log files can help diagnose the
vast majority of the problems faced by beginning- to
intermediate-level Samba administrators. Samba is quite flexible when
it comes to logging. You can set up the server to log as little or as
much information as you want. Using substitution variables in the
Samba configuration file allows you to isolate individual logs for
each system, share, or combination thereof.
Logs are placed in /usr/local/samba/var/smbd.log
and /usr/local/samba/var/nmbd.log by default.
You can specify a log directory to use with the
-l flag on the command line when starting the
Samba daemons. For example:
#smbd -l /var/log/samba
#nmbd -l /var/log/samba
Alternatively, you can override the location and name using the
log
file
configuration
option in smb.conf. This option accepts all the
substitution variables, so you could easily have the server keep a
separate log for each connecting client system by specifying the
following:
[global] log file = %m.log
Another useful trick is to have the server keep a log for each
service (share) that is offered, especially if you suspect a
particular share is causing trouble. To do this, use the
%S
variable, like this:
[global] log file = %S.log
Log levels
The level of logging that Samba uses
can be set in the smb.conf file using the global
log
level
or
debug
level
option; they are
equivalent. The logging level is an integer that can range from 0 to
10. At level 0, no logging is done. Higher values result in more
voluminous logging. For example, let’s assume that
we will use a Windows client to browse a directory on a Samba server.
For a small amount of log information, you can use
log
level
=
1
, which instructs Samba to show only cursory
information, in this case only the connection itself:
05/25/02 22:02:11 server (192.168.236.86) connect to service public as user pcguest (uid=503,gid=100) (pid 3377)
Higher debug levels produce more detailed information. Usually, you
won’t need more than level 3, which is fully
adequate for most Samba administrators. Levels above 3 are used by
the developers and dump enormous amounts of cryptic information.
Here is an example of output at levels 2 and 3 for the same
operation. Don’t worry if you don’t
understand the intricacies of an SMB connection; the point is simply
to show you what types of information are shown at the different
logging levels:
/* Level 2 */ Got SIGHUP Processing section "[homes]" Processing section "[public]" Processing section "[temp]" Allowed connection from 192.168.236.86 (192.168.236.86) to IPC$ Allowed connection from 192.168.236.86 (192.168.236.86) to IPC/ /* Level 3 */ 05/25/02 22:15:09 Transaction 63 of length 67 switch message SMBtconX (pid 3377) Allowed connection from 192.168.236.86 (192.168.236.86) to IPC$ ACCEPTED: guest account and guest ok found free connection number 105 Connect path is /tmp chdir to /tmp chdir to / 05/25/02 22:15:09 server (192.168.236.86) connect to service IPC$ as user pcguest (uid=503,gid=100) (pid 3377) 05/25/02 22:15:09 tconX service=ipc$ user=pcguest cnum=105 05/25/02 22:15:09 Transaction 64 of length 99 switch message SMBtrans (pid 3377) chdir to /tmp trans <PIPELANMAN> data=0 params=19 setup=0 Got API command 0 of form <WrLeh> <B13BWz> (tdscnt=0,tpscnt=19,mdrcnt=4096,mprcnt=8) Doing RNetShareEnum RNetShareEnum gave 4 entries of 4 (1 4096 126 4096) 05/25/02 22:15:11 Transaction 65 of length 99 switch message SMBtrans (pid 3377) chdir to / chdir to /tmp trans <PIPELANMAN> data=0 params=19 setup=0 Got API command 0 of form <WrLeh> <B13BWz> (tdscnt=0,tpscnt=19,mdrcnt=4096,mprcnt=8) Doing RNetShareEnum RNetShareEnum gave 4 entries of 4 (1 4096 126 4096) 05/25/02 22:15:11 Transaction 66 of length 95 switch message SMBtrans2 (pid 3377) chdir to / chdir to /pcdisk/public call_trans2findfirst: dirtype = 0, maxentries = 6, close_after_first=0, close_if_end = 0 requires_resume_key = 0 level = 260, max_data_bytes = 2432 unix_clean_name [./DESKTOP.INI] unix_clean_name [desktop.ini] unix_clean_name [./] creating new dirptr 1 for path ./, expect_close = 1 05/25/02 22:15:11 Transaction 67 of length 53 switch message SMBgetatr (pid 3377) chdir to / [... deleted ...]
We cut off this listing after the first packet because it runs on for
many pages. However, be aware that log levels above 3 will quickly
consume disk space with megabytes of excruciating detail concerning
Samba’s internal operations. Log level 3 is
extremely useful for following exactly what the server is doing, and
most of the time it will be obvious where an error occurs by glancing
through the log file.
Using a high log level (3 or above) will
seriously slow down the Samba server. Remember
that every log message generated causes a write to disk (an
inherently slow operation) and log levels greater than 2 produce
massive amounts of data. Essentially, you should turn on logging
level 3 only when you’re actively tracking a problem
in the Samba server.
Unix Utilities
Sometimes it’s useful to use a tool outside the
Samba suite to examine what’s happening inside the
server. Three diagnostic tools can be of particular help in debugging
Samba troubles: trace,
tcpdump, and Ethereal.
Using trace
The trace command masquerades under several
different names, depending on the operating system you are using. On
Linux it will be
strace; on Solaris you’ll use
truss; SGI will have
padc and
par; and HP-UX will have
trace or
tusc. All have essentially the same
function, which is to display each operating system function call as
it is executed. This allows you to follow the execution of a program,
such as the Samba server, and often pinpoints the exact call that is
causing the difficulty.
One problem that trace can highlight is an
incorrect version of a dynamically linked library. This can happen if
you’ve downloaded prebuilt binaries of Samba.
You’ll typically see the offending call at the end
of the trace, just before the program
terminates.
A sample strace output for the Linux operating
system follows. This is a small section of a larger file created
during the opening of a directory on the Samba server. Each line
lists a system call and includes its parameters and the return value.
If there was an error, the error value (e.g.,
ENOENT
) and its explanation are also shown. You
can look up the parameter types and the errors that can occur in the
appropriate trace manual page for the operating
system you are using.
chdir("/pcdisk/public") = 0 stat("mini/desktop.ini", 0xbffff7ec) = -1 ENOENT (No such file or directory) stat("mini", {st_mode=S_IFDIR|0755, st_size=1024, ...}) = 0 stat("mini/desktop.ini", 0xbffff7ec) = -1 ENOENT (No such file or directory) open("mini", O_RDONLY) = 5 fcntl(5, F_SETFD, FD_CLOEXEC) = 0 fstat(5, {st_mode=S_IFDIR|0755, st_size=1024, ...}) = 0 lseek(5, 0, SEEK_CUR) = 0 SYS_141(0x5, 0xbfffdbbc, 0xedc, 0xbfffdbbc, 0x80ba708) = 196 lseek(5, 0, SEEK_CUR) = 1024 SYS_141(0x5, 0xbfffdbbc, 0xedc, 0xbfffdbbc, 0x80ba708) = 0 close(5) = 0 stat("mini/desktop.ini", 0xbffff86c) = -1 ENOENT (No such file or directory) write(3, "#377SMB10122001"..., 39) = 39 SYS_142(0xff, 0xbffffc3c, 0, 0, 0xbffffc08) = 1 read(3, "?", 4) = 4 read(3, "377SMBu"..., 63) = 63 time(NULL) = 896143871
This example shows several stat() calls failing
to find the files they were expecting. You don’t
have to be an expert to see that the file
desktop.ini is missing from that directory. In
fact, many difficult problems can be identified by looking for
obvious, repeatable errors with trace. Often,
you need not look further than the last message before a crash.
Using tcpdump
The tcpdump program, as extended by Andrew
Tridgell,
allows you to monitor SMB network
traffic in real time. A variety of output formats are available, and
you can filter the output to look at only a particular type of
traffic. You can examine all conversations between client and server,
including SMB and NMB broadcast messages. While its troubleshooting
capabilities lie mainly at the OSI network layer, you can still use
its output to get a general idea of what the server and client are
attempting to do.
A sample tcpdump log follows. In this instance,
the client has requested a directory listing, and the server has
responded appropriately, giving the directory names
homes
, public
,
IPC$
, and temp
(we’ve added a few explanations on the right):
$tcpdump -v -s 255 -i eth0 port not telnet
SMB PACKET: SMBtrans (REQUEST) Request packet SMB Command = 0x25 Request was ls or dir [000] 01 00 00 10 .... >>> NBT Packet Outer frame of SMB packet NBT Session Packet Flags=0x0 Length=226 [lines skipped] SMB PACKET: SMBtrans (REPLY) Beginning of a reply to request SMB Command = 0x25 Command was an ls or dir Error class = 0x0 Error code = 0 No errors Flags1 = 0x80 Flags2 = 0x1 Tree ID = 105 Proc ID = 6075 UID = 100 MID = 30337 Word Count = 10 TotParamCnt=8 TotDataCnt=163 Res1=0 ParamCnt=8 ParamOff=55 Res2=0 DataCnt=163 DataOff=63 Res3=0 Lsetup=0 Param Data: (8 bytes) [000] 00 00 00 00 05 00 05 00 ........ Data Data: (135 bytes) Actual directory contents: [000] 68 6F 6D 65 73 00 00 00 00 00 00 00 00 00 00 00 homes... ........ [010] 64 00 00 00 70 75 62 6C 69 63 00 00 00 00 00 00 d...publ ic...... [020] 00 00 00 00 75 00 00 00 74 65 6D 70 00 00 00 00 ....u... temp.... [030] 00 00 00 00 00 00 00 00 76 00 00 00 49 50 43 24 ........ v...IPC$ [040] 00 00 00 00 00 00 00 00 00 00 03 00 77 00 00 00 ........ ....w... [050] 64 6F 6E 68 61 6D 00 00 00 00 00 00 00 00 00 00 donham.. ........ [060] 92 00 00 00 48 6F 6D 65 20 44 69 72 65 63 74 6F ....Home Directo [070] 72 69 65 73 00 00 00 49 50 43 20 53 65 72 76 69 ries...I PC Servi [080] 63 65 20 28 53 61 6D ce (Sam
This is more of the same debugging session as we saw before with the
trace command: the listing of a directory. The options
we used were -v (verbose), -i
eth0 to tell tcpdump on which
interface to listen (an Ethernet port), and -s
255 to tell it to save the first 255 bytes of each packet
instead of the default: the first 68. The option
port
not
telnet
is used to avoid screens of telnet traffic,
because we were logged in to the server remotely. The
tcpdump program actually has quite a number of
options to filter just the traffic you want to look at. If
you’ve used snoop or
etherdump, it will look vaguely familiar.
You can download the modified tcpdump from the
Samba FTP server, located at
ftp://samba.anu.edu.au/pub/samba/tcpdump-smb.
Other versions might not include support for the SMB protocol; if you
don’t see output such as that shown in the example,
you’ll need to use the SMB-enabled version.
Using Ethereal
Ethereal (http://www.ethereal.com) is a GUI-based
utility that performs the same basic function as
tcpdump. You might prefer Ethereal because it is
much easier to use. Once you have Ethereal running, just do the
following:
-
Select Start from the Capture menu.
-
Click the OK button in the dialog box that appears. This will bring
up a dialog box showing how many packets Ethereal has seen. Perform
the actions on the system(s) in your network to reproduce the problem
you are analyzing. -
Click the Stop button in the Ethereal dialog box to make it finish
collecting data. -
In the main Ethereal window, click any item in the upper window to
view it in the lower window. In the lower window, click any of the
boxes containing a plus sign (+
) to expand the
view.
Ethereal does a good job of translating the content of the packets it
encounters into human-readable format, and you should have little
trouble seeing what happened on the network during the capture
period.
The Fault Tree
The fault
tree presented in this section is for diagnosing and fixing problems
that occur when you’re installing and reconfiguring
Samba. It’s an expanded form of the trouble and
diagnostic document DIAGNOSIS.txt, which is part
of the Samba distribution.
Before you set out to troubleshoot any part of the Samba suite, you
should know the following information:
-
Your client IP address (we use 192.168.236.10)
-
Your server IP address (we use 192.168.236.86)
-
The netmask for your network (typically 255.255.255.0)
-
Whether the systems are all on the same subnet (ours are)
For clarity, we’ve renamed the server in the
following examples to server.example.com
, and the
client system to client.example.com
.
Troubleshooting Low-Level IP
The
first series of tests is that of the low-level services that Samba
needs to run. The tests in this section verify that:
-
The IP software works
-
The Ethernet hardware works
-
Basic name service is in place
Subsequent sections add TCP software, the Samba daemons
smbd and nmbd, host-based
access control, authentication and per-user access control, file
services, and browsing. The tests are described in considerable
detail to make them understandable by both technically oriented end
users and experienced systems and network administrators.
Testing the networking software with ping
The first command to enter
on both the server and the client is
ping
127.0.0.1
. This pings the loopback address and
indicates whether any networking support is functioning. On Unix, you
can use ping
127.0.0.1
with the
statistics option and interrupt it after a few lines. On Sun
workstations, the command is typically
/usr/etc/ping
-s
127.0.0.1
; on Linux, just ping
127.0.0.1
. On Windows clients, run
ping
127.0.0.1
in an MS-DOS
(command prompt) window, and it will stop by itself after four lines.
Here is an example on a Linux server:
$ping 127.0.0.1
PING localhost: 56 data bytes 64 bytes from localhost (127.0.0.1): icmp-seq=0. time=1. ms 64 bytes from localhost (127.0.0.1): icmp-seq=1. time=0. ms 64 bytes from localhost (127.0.0.1): icmp-seq=2. time=1. ms ^C ----127.0.0.1 PING Statistics---- 3 packets transmitted, 3 packets received, 0% packet loss round-trip (ms) min/avg/max = 0/0/1
If you get «ping: no answer from . . .
» or «100% packet
loss,» you have no IP networking installed on the
system. The address 127.0.0.1
is the internal
loopback address and doesn’t depend on the computer
being physically connected to a network. If this test fails, you have
a serious local problem. TCP/IP either isn’t
installed or is seriously misconfigured. See your operating system
documentation if it’s a Unix server. If
it’s a Windows client, follow the instructions in
Chapter 3 to install networking support.
TIP
If you’re the network manager,
some good references are Craig Hunt’s
TCP/IP Network Administration, Chapter 11, and Craig Hunt and Robert Bruce
Thompson’s Windows NT TCP/IP Network
Administration, both published by
O’Reilly.
Testing local name services with ping
Next, try to ping
localhost
on the Samba server. The
localhost
hostname is the conventional hostname
for the 127.0.0.1
loopback interface, and it
should resolve to that address. After typing ping
localhost
, you should see output similar to the
following:
$ping localhost
PING localhost: 56 data bytes 64 bytes from localhost (127.0.0.1): icmp-seq=0. time=0. ms 64 bytes from localhost (127.0.0.1): icmp-seq=1. time=0. ms 64 bytes from localhost (127.0.0.1): icmp-seq=2. time=0. ms ^C
If this succeeds, try the same test on the client. Otherwise:
-
If you get «unknown host:
localhost,» there is a problem resolving the
hostname localhost into a valid IP address.
(This might be as simple as a missing entry in a local
hosts file.) From here, skip down to
Section 12.2.7 later in this chapter. -
If you get «ping: no answer,» or
«100% packet loss,» but pinging
127.0.0.1
worked, name services is resolving to an
address, but it isn’t the correct one. Check the
file or database (typically /etc/hosts on a Unix
system) that the name service is using to resolve addresses to ensure
that the entry is correct.
Testing connections with ping
Now, ping the server by name (instead
of its IP address)—once from the server and once from the
client. This is the general test for working network hardware:
$ping server
PING server.example.com: 56 data bytes 64 bytes from server.example.com (192.168.236.86): icmp-seq=0. time=1. ms 64 bytes from server.example.com (192.168.236.86): icmp-seq=1. time=0. ms 64 bytes from server.example.com (192.168.236.86): icmp-seq=2. time=1. ms ^C ----server.example.com PING Statistics---- 3 packets transmitted, 3 packets received, 0% packet loss round-trip (ms) min/avg/max = 0/0/1
If successful, this test tells us five things:
-
The hostname (e.g.,
server
) is being found by your
local name server. -
The hostname has been expanded to the full name (e.g.,
server.example.com
). -
Its address is being returned (
192.168.236.86
). -
The client has sent the Samba server four 56-byte UDP/IP packets.
-
The Samba server has replied to all four packets.
If this test isn’t successful, one of several things
can be wrong with the network:
-
First, if you get
ping
:no
answer
, or100%
packet
loss
,
you’re not connecting to the network, the other
system isn’t connecting, or one of the addresses is
incorrect. Check the addresses that the ping
command reports on each system, and ensure that they match the ones
you set up initially.If not, there is at least one mismatched address between the two
systems. Try entering the commandarp
-a
, and see if there is an entry for the other
system. (The arp command stands for the Address
Resolution Protocol. Thearp
-a
command lists all the addresses known on the local system.) Here are
some things to try:-
If you receive a message like
192.168.236.86
at
(incomplete)
, the Ethernet
address of 192.168.236.86 is unknown. This indicates a complete lack
of connectivity, and you’re likely having a problem
at the very bottom of the TCP/IP protocol stack—the Ethernet
interface layer. This is discussed in Chapters 5 and 6 of
TCP/IP Network Administration
(O’Reilly). -
If you receive a response similar to server
(192.168.236.86)
at
8:0:20:12:7c:94
, the server has been reached at
some time, or another system is answering on its behalf. However,
this means that ping should have worked: you may
have an intermittent networking or ARP problem. -
If the IP address from ARP doesn’t match the
addresses you expected, investigate and correct the addresses
manually.
-
-
If each system can ping itself but not another, something is wrong on
the network between them. -
If you get
ping
:network
unreachable
orICMP
Host
Unreachable
,
you’re not receiving an answer, and more than one
network is probably involved.In principle, you shouldn’t try to troubleshoot SMB
clients and servers on different networks. Try to test a server and
client that are on the same network:-
First, perform the tests for
ping
:
no
answer
described earlier in
this section. If this doesn’t identify the problem,
the remaining possibilities are the following: an address is wrong,
your netmask is wrong, a network is down, or the packets have been
stopped by a firewall. -
Check both the address and the netmasks on source and destination
systems to see if something is obviously wrong. Assuming both systems
really are on the same network, they both should have the same
netmasks, and ping should report the correct
addresses. If the addresses are wrong, you’ll need
to correct them. If they are correct, the programs might be confused
by an incorrect netmask. See Section 12.2.8.1, later in this chapter. -
If the commands are still reporting that the network is unreachable
and neither of the previous two conditions are in error, one network
really might be unreachable from the other. This, too, is an issue
for the network manager.
-
-
If you get
ICMP
Administratively
Prohibited
,
you’ve struck a firewall of some sort or a
misconfigured router. You will need to speak to your network security
officer. -
If you get
ICMP
Host
redirect
and ping reports
packets getting through, this is generally harmless:
you’re simply being rerouted over the network. -
If you get a host redirect and no ping
responses, you are being redirected, but no one is responding. Treat
this just like theNetwork
unreachable
response, and check your addresses and
netmasks. -
If you get
ICMP
Host
Unreachable
from
gateway
gateway
name
, ping packets are being routed to another
network, but the other system isn’t responding and
the router is reporting the problem on its behalf. Again, treat this
like aNetwork
unreachable
response, and start checking addresses and netmasks. -
If you get
ping
:unknown
host
hostname
, your
system’s name is not known. This tends to indicate a
name service problem, which didn’t affect
localhost
. Have a look at Section 12.2.7, later in this chapter. -
If you get a partial success—with some pings failing but others
succeeding—you have either an intermittent problem between the
systems or an overloaded network. Ping a bit longer, and see if more
than about three percent of the packets fail. If so, check it with
your network manager: a problem might just be starting. However, if
only a few fail, or if you happen to know some massive network
program is running, don’t worry unduly. The ICMP
(and UDP) protocols used by ping are allowed to
drop occasional packets. -
If you get a response such as
smtsvr.antares.net
is
alive
when you actually
pingedclient.example.com
, either
you’re using someone else’s address
or the system has multiple names and addresses. If the address is
wrong, the name service is clearly the culprit;
you’ll need to change the address in the name
service database to refer to the correct system. This is discussed in
Section 12.2.7, later in this
chapter.Servers are often multihomed —i.e.,
connected to more than one network, with different names on each net.
If you are getting a response from an unexpected name on a multihomed
server, look at the address and see if it’s on your
network (see Section 12.2.8.1, later in this chapter). If
so, you should use that address, rather than one on a different
network, for both performance and reliability reasons.Servers can also have multiple names for a single Ethernet address,
especially if they are web servers. This is harmless, albeit
startling. You probably will want to use the official (and permanent)
name, rather than an alias that might change. -
If everything works but the IP address reported is
127.0.0.1
, you have a name service error. This
typically occurs when an operating-system installation program
generates an /etc/hosts line similar to
127.0.0.1
localhost
hostname.domainname. The localhost line should
say127.0.0.1
localhost
or
127.0.0.1
localhost
loghost
. Correct it, lest it cause failures to
negotiate who is the master browse list holder and who is the master
browser. It can also cause (ambiguous) errors in later tests.
If this worked from the server, repeat it from the client.
Troubleshooting TCP
Now that
you’ve tested IP, UDP, and a name service with
ping, it’s time to test TCP.
Browsing and ping use ICMP and UDP; file and
print services (shares) use TCP. Both depend on IP as a lower layer,
and all four depend on name services. Testing TCP is most
conveniently done using the FTP program.
Testing TCP with FTP
Try connecting via FTP, once from the server to itself, and once from
the client to the server:
$ftp server
Connected to server.example.com. 220 server.example.com FTP server (Version 6.2/OpenBSD/Linux-0.10) ready. Name (server:davecb): 331 Password required for davecb. Password: 230 User davecb logged in. ftp>quit
221 Goodbye.
If this worked, skip to the next section, Section 12.2.4. Otherwise:
-
If you received the message
server
:
unknown
host
, name service has
failed. Go back to the corresponding ping step,
Section 12.2.2.2, and rerun those tests
to see why name lookup failed. -
If you received
ftp
:connect
:
Connection
refused
, the system
isn’t running an FTP daemon. This is mildly unusual
on Unix servers. Optionally, you might try this test by connecting to
the system using telnet instead of
ftp; the messages are very similar, and
telnet uses TCP as well. -
If there was a long pause, and then
ftp
:
connect
:Connection
timed
out
, the system
isn’t reachable. Return to Section 12.2.2.4. -
If you received
530
Logon
Incorrect
, you connected successfully, but
you’ve just found a different problem. You likely
provided an incorrect username or password. Try again, making sure
you use your username from the Unix server and type your password
correctly.
Troubleshooting Server Daemons
Once
you’ve confirmed that TCP networking is working
properly, the next step is to make sure the daemons are running on
the server. This takes three separate tests because no single one of
the following will decisively prove that they’re
working correctly.
To be sure they’re running, you need to find out
whether the daemons:
-
Have started
-
Are registered or bound to a TCP/IP port by the operating system
-
Are actually paying attention
Looking for daemons bound to ports
Next, the daemons have to be registered
with the operating system so that they can get access to TCP/IP
ports. The netstat command will tell you if this
has been done. Run the command netstat
-a
on the server, and look for lines mentioning
netbios
, 137
, or
139
:
$netstat -a
Active Internet connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) udp 0 0 *.137 *.* tcp 0 0 *.139 *.* LISTEN tcp 8370 8760 server.139 client.1439 ESTABLISHED
Among similar lines, there should be at least one UDP line for
*.netbios-
or *.137
. This
indicates that the nmbd server is registered and
(we hope) is waiting to answer requests. There should also be at
least one TCP line mentioning *.netbios-
or
*.139
, and it will probably be in the LISTEN
state. This means that smbd is up and listening
for connections.
There might be other TCP lines indicating connections from
smbd to clients, one for each client. These are
usually in the ESTABLISHED state. If there are
smbd lines in the ESTABLISHED state,
smbd is definitely running. If there is only one
line in the LISTEN state, we’re not sure yet. If
both of the lines are missing, a daemon has not succeeded in
starting, so it’s time to check the logs and then go
back to Chapter 2.
If there is a line for each client, it might be coming either from a
Samba daemon or from the master IP daemon,
inetd. It’s quite possible that
your inetd startup file contains lines that
start Samba daemons without your realizing it; for instance, the
lines might have been placed there if you installed Samba as part of
a Linux distribution. The daemons started by
inetd prevent ours from running. This problem
typically produces log messages such as bind
failed
on
port
139
socket
addr=0
(Address
already
in
use)
.
Check your /etc/inetd.conf ; unless
you’re intentionally starting the daemons from
there, netbios-ns
(UDP port 137) or
netbios-ssn
(tcp port 139) servers should be
mentioned there. If your system is providing an SMB daemon via
inetd, lines such as the following will appear
in the inetd.conf file:
netbios-ssn stream tcp nowait root /usr/local/samba/bin/smbd smbd netbios-ns dgram udp wait root /usr/local/samba/bin/nmbd nmbd
If your system uses xinetd instead of
inetd, see Chapter 2 for
details concerning its configuration.
Testing daemons with testparm
Once you know
there’s a daemon, you should always run
testparm, in hopes of getting something such as
the following:
$testparm
Load smb config files from /opt/samba/lib/smb.conf Processing section "[homes]" Processing section "[printers]" ... Processing section "[tmp]" Loaded services file OK. ...
The testparm program normally reports the
processing of a series of sections and responds with
Loaded
services
file
OK
if it succeeds. If not,
it reports one or more of the following messages, which also appear
in the logs as noted:
- Allow/Deny connection from account (n) to service
-
A testparm-only message produced if you have
valid
user
or
invalid
user
options set in
your smb.conf. You will want to make sure that
you are on the valid user list, and thatroot
,
bin
, etc., are on the invalid user list. If you
don’t, you will not be able to connect, or users who
shouldn’t will be able to. - Warning: You have some share names that are longer than eight chars
-
For anyone using Windows for Workgroups and older clients. They fail
to connect to shares with long names, producing an overflow message
that sounds confusingly like a memory overflow. - Warning: [name] service MUST be printable!
-
A printer share lacks a
printable
=
yes
option. - No path in service name using [name]
-
A file share doesn’t know which directory to provide
to the user, or a print share doesn’t know which
directory to use for spooling. If no path is specified, the service
will try to run with a path of /tmp, which might
not be what you want. - Note: Servicename is flagged unavailable
-
Just a reminder that you have used the
available
=
no
option in a share. - Can’t find include file [name]
-
A configuration file referred to by an
include
option did not exist. If you were including the file unconditionally,
this is an error and probably a serious one: the share will not have
the configuration you intended. If you were including it based on one
of the%
variables, such as%a
(architecture), you will need to decide whether, for example, a
missing Windows for Workgroups configuration file is a problem. It
often isn’t. - Can’t copy service name, unable to copy to itself
-
You tried to copy an smb.conf section into
itself. - Unable to copy service—source not found: [name]
-
Indicates a missing or misspelled section in a
copy
=
option. - Ignoring unknown parameter name
-
Typically indicates an obsolete, misspelled, or unsupported option.
- Global parameter name found in service section
-
Indicates that a global-only parameter has been used in an individual
share. Samba ignores the parameter.
After the testparm test, repeat it with
(exactly) three parameters: the name of your
smb.conf file, the name of your client, and its
IP address:
#testparm /usr/local/samba/lib/smb.conf client 192.168.236.10
This will run one more test that checks the hostname and address
against hosts
allow
and
hosts
deny
options and might
produce the Allow
connection
from
hostname
to
service
and/or
Deny
connection
from
hostname
to
service
messages for the
client system. These messages indicate that you have
hosts
allow
and/or
hosts
deny
options in your
smb.conf, and they prohibit access from the
client system.
Troubleshooting SMB Connections
Now
that you know the servers are up, you need to make sure
they’re running properly. We start by placing a
simple smb.conf file in the
/usr/local/samba/lib directory.
Testing locally with smbclient
The first test is to ensure that the
server can list its own services (shares). Run the command
smbclient
-L
localhost
-U%
to connect to the
server from itself, and specify the guest user. You should see the
following:
$smbclient -L localhost -U%
Server time is Wed May 27 17:57:40 2002 Timezone is UTC-4.0 Server=[localhost] User=[davecb] Workgroup=[EXAMPLE] Domain=[EXAMPLE] Sharename Type Comment --------- ----- ---------- temp Disk IPC$ IPC IPC Service (Samba 1.9.18) homes Disk Home directories This machine does not have a browse list
If you received this output, move on to the next section, Section 12.2.5.3. On the other hand, if you
receive an error, check the following:
-
If you get
Get_hostbyname
:
unknown
host
localhost
, either you’ve spelled
its name wrong or there actually is a problem (which should have been
seen back in Section 12.2.2.2). In the
latter case, move on to Section 12.2.7, later in this chapter. -
If you get
Connect
error
:
Connection
refused
, the server
was found, but it wasn’t running an
nmbd daemon. Skip back to
Section 12.2.4,
earlier in this chapter, and retest the daemons. -
If you get the message
Your
server
software
is
being
unfriendly
, the initial session request packet got
a garbage response from the server. The server might have crashed or
started improperly. The common causes of this can be discovered by
scanning the logs for the following:-
Invalid command-line parameters to smbd ; see
the smbd manual page. -
A fatal problem with the smb.conf file that
prevents the startup of smbd. Always check your
changes with testparm, as was done in Section 12.2.4.5, earlier in this chapter. -
Missing directories where Samba is supposed to keep its log and lock
files. -
The presence of a server already on the port (139 for
smbd, 137 for nmbd ),
preventing the daemon from starting.
-
-
If you’re using inetd (or
xinetd ) instead of standalone daemons, be sure to check your
/etc/inetd.conf (or xinetd configuration files)
and /etc/services entries against their manual
pages for errors as well. -
If you get a
Password
: prompt, your guest account
is not set up properly. The -U% option tells
smbclient to do a «null
login,» which requires that the guest account be
present but does not require it to have any privileges. -
If you get the message
SMBtconX
failed
.ERRSRV--ERRaccess
, you
aren’t permitted access to the server. This normally
means you have ahosts
allow
option that doesn’t include the server or a
hosts
deny
option that does.
Recheck with the commandtestparm
smb.conf
your_hostname
your_ip_address (see
Section 12.2.4.5),
and correct any unintended prohibitions.
Testing connections with smbclient
Run the command
smbclient
\
servertemp
to connect to the server’s [temp]
share and to see if you can connect to a file service. You should get
the following response:
$smbclient '\servertemp'
Server time is Tue May 5 09:49:32 2002 Timezone is UTC-4.0 Password: smb: > quit
You might receive the following errors:
-
If you get
Get_Hostbyname
:
Unknown
host
name
,Connect
error
:Connection
refused
, orYour
server
software
is
being
unfriendly
, see the previous section,
Section 12.2.5.2, for
the diagnoses. -
If you get the message
servertemp
:
Not
enough
`
‘
characters
in
service
, you likely didn’t quote
the address, so Unix stripped off backslashes. You can also write the
command:smbclient \\server\temp
or:
smbclient //server/temp
Now, provide your Unix account password to the
Password
: prompt. If you then get an
smb
: >
prompt, it worked.
Enter quit
and continue on to the next section,
Section 12.2.5.4. If
you got SMBtconX
failed
.
ERRSRV--ERRinvnetname
, the problem can be any of
the following:
-
A wrong share name: you might have spelled it wrong, it might be too
long, it might be in mixed case, or it might not be available. Check
that it’s what you expect with
testparm (see the earlier section, Section 12.2.4.5). -
A
security
=
share
parameter in your Samba configuration file,
in which case you might have to add-U
your_account to the
smbclient command. -
An erroneous username.
-
An erroneous password.
-
An
invalid
users
or
valid
users
option in your
smb.conf file that doesn’t
allow your account to connect. Recheck using
testparm
smb.conf
your_hostname your_ip_address (see the
earlier section, Section 12.2.4.5). -
A
valid
hosts
option that
doesn’t include the server, or an
invalid
hosts
option that does.
Also test this with testparm. -
A problem in authentication, such as if shadow passwords or the
Password Authentication Module (PAM) is used on the server, but Samba
is not compiled to use it. This is rare, but it occasionally happens
when a SunOS 4 Samba binary (with no shadow passwords) is run without
recompilation on a Solaris system (with shadow passwords). -
The
encrypted
passwords
=
yes
option is in the
configuration file, but no password for your account is in the
smbpasswd file. -
You have a null password entry, either in Unix
/etc/passwd or in the
smbpasswd file. -
You are connecting to
[temp]
, and you do not have
theguest
ok
=
yes
option in the
[temp]
section of the
smb.conf file. -
You are connecting to
[temp]
before connecting to
your home directory, and your guest account isn’t
set up correctly. If you can connect to your home directory and then
connect to[temp]
, that’s the
problem. See Chapter 2 for more information on
creating a basic Samba configuration file.A bad guest account will also prevent you from printing or browsing
until after you’ve logged in to your home directory.
There is one more reason for this failure that has nothing at all to
do with passwords: the path
parameter in your
smb.conf file might point somewhere that
doesn’t exist. This will not be diagnosed by
testparm, and most SMB clients
can’t distinguish it from other types of bad user
accounts. You will have to check it manually.
Once you have connected to [temp]
successfully,
repeat the test, this time logging in to your home directory (e.g.,
map network drive
serverdavecb
). If you
have to change anything to get that to work, retest
[temp]
again afterward.
Testing connections with net use
Run the command
net
use
*
server
temp
on the Windows client to see if it can connect to the server. You
should be prompted for a password, then receive the response
The
command
was
completed
successfully
.
If that worked, continue with the steps in the next section, Section 12.2.5.5. Otherwise:
-
If you get
The
specified
shared
directory
cannot
be
found
, orCannot
locate
specified
share
name
, the directory name
is either misspelled or not in the smb.conf
file. This message can also warn of a name that is in mixed case,
including spaces, or that is longer than eight characters. -
If you get
The
computer
name
specified
in
the
network
path
cannot
be
located
orCannot
locate
specified
computer
, the directory name has been misspelled,
the name service has failed, there is a networking problem, or the
hosts
deny
option includes your
host.-
If it is not a spelling mistake, you need to double back at least to
Section 12.2.5.3 to
investigate why it doesn’t connect. -
If smbclient does work, there is a name service
problem with the client name service, and you need to go forward to
Section 12.2.6.2 and see if
you can look up both the client and server with
nmblookup.
-
-
If you get
The
password
is
invalid
for
serverusername
, your
locally cached copy on the client doesn’t match the
one on the server. You will be prompted for a replacement.TIP
Each Windows 95/98/Me client keeps a local
password file, but it’s really
just a cached copy of the password it sends to Samba and NT/2000/XP
servers to authenticate you. That’s what is being
prompted for here. You can still log on to a Windows system without a
password (but not to NT/2000/XP).If you provide your password and it still fails, your password is not
being matched on the server, you have avalid
users
orinvalid
users
list denying you permission, NetBEUI is
interfering, or the encrypted password problem described in the next
paragraph exists. -
If your client is Windows NT 4.0, NT 3.5 with Patch 3, Windows 95
with Patch 3, Windows 98, any of these with Internet Explorer 4.0, or
any subsequent version of Windows, the system will default to
Microsoft encryption for passwords. In general, if you have installed
a major Microsoft product on any of the older Windows versions, you
might have applied an update and turned on encrypted passwords. If
the client is defaulting to encrypted passwords, you will need to
specifyencrypt
passwords
=
yes
in your Samba
configuration file if you are using a version of Samba prior to Samba
3.0.TIP
Because of Internet Explorer’s willingness to honor
URLs such as file://somehost/somefile by making
SMB connections, clients up to and including Windows 95 Patch Level 2
would happily send your password, in plain text, to SMB servers
anywhere on the Internet. This was considered a bad idea, and
Microsoft switched to using only encrypted passwords in the SMB
protocol. All subsequent releases of Microsoft’s
products have included this correction. -
If you have a mixed-case password on Unix, the client is probably
sending it in all one case. If changing your password to all one case
works, this was the problem. Regrettably, all but the oldest clients
support uppercase passwords, so Samba will try once with the password
in uppercase and once in lowercase. If you wish to use mixed-case
passwords, see thepassword
level
option in Chapter 9 for a
workaround. -
You might have a
valid
users
problem, as tested with smbclient (see the
earlier section, Section 12.2.5.3). -
You might have the NetBEUI protocol bound to the Microsoft client.
This often produces long timeouts and erratic failures and is known
to have caused failures to accept passwords in the past. Unless you
absolutely need the NetBEUI protocol, remove it.
TIP
The term «bind» is used here to
mean connecting one piece of software to another. When configured
correctly, the Microsoft SMB client is «bound
to» TCP/IP in the bindings section of the TCP/IP
properties panel under the Windows 95/98/Me Network icon in the
Control Panel. TCP/IP in turn is bound to an Ethernet card. This is
not the same sense of the word as binding an SMB daemon to a TCP/IP
port.
Testing connections with Windows Explorer
Start Windows Explorer
(not Internet Explorer), select Map Network Drive from the Tools
menu, and specify the UNC for one of your shares on the Samba server
to see if you can make Explorer connect to it. If so,
you’ve succeeded and can skip to the next section,
Section 12.2.6.
Windows Explorer is a rather poor diagnostic tool: it tells you that
something’s wrong, but rarely what it is. If you get
a failure, you’ll need to track it down with the
Windows net use command, which has far superior
error reporting:
-
If you get
The
password
for
this
connection
that
is
in
your
password
file
is
no
longer
correct
, you might have any of the following:-
Your locally cached copy on the client doesn’t match
the one on the server. -
You didn’t provide a username and password when
logging on to the client. Some versions of Explorer will continue to
send a null username and password, even if you provide a password. -
You have misspelled the password.
-
You have an
invalid
users
or
valid
users
list denying
permission. -
Your client is defaulting to encrypted passwords, but Samba is
configured with theencrypt
passwords
=
no
configuration file parameter. -
You have a mixed-case password, which the client is supplying in all
one case.
-
-
If you get
The
network
name
is
either
incorrect
,
or
a
network
to
which
you
do
not
have
full
access
, or
Cannot
locate
specified
computer
, you might
have any of the following:-
Misspelled name
-
Malfunctioning service
-
Failed share
-
Networking problem
-
Bad
path
parameter in
smb.conf -
hosts
deny
line that excludes
you
-
-
If you get
You
must
supply
a
password
to
make
this
connection
, the password on the client is out of
synchronization with the server, or this is the first time
you’ve tried from this client system and the client
hasn’t cached it locally yet. -
If you get
Cannot
locate
specified
share
name
, you have a wrong share name or a syntax
error in specifying it, a share name longer than eight characters, or
one containing spaces or in mixed case.
Once you can reliably connect to the share, try again, this time
using your home directory. If you have to change something to get
home directories working, retest with the first share, and vice
versa, as we showed in the earlier section, «Testing
connections with net use.» As always, if Explorer
fails, drop back to that section and debug the connection there.
Troubleshooting Browsing
Finally, we
come to browsing. We’ve left this for last, not
because it is the most difficult, but because it’s
both optional and partially dependent on a protocol that
doesn’t guarantee delivery of a packet. Browsing is
hard to diagnose if you don’t already know that all
the other services are running.
Browsing is purely optional: it’s just a way to find
the servers on your network and the shares that they provide. Unix
has nothing of the sort and happily does without. Browsing also
assumes all your systems are on a local area network (LAN) where
broadcasts are allowable.
First, the browsing mechanism identifies a system using the
unreliable UDP protocol; it then makes a normal (reliable) TCP/IP
connection to list the shares the system provides.
Testing browsing with smbclient
We’ll start with
testing the reliable connection first. From the server, try listing
its own shares using smbclient with a
-L
option and your server’s name.
You should get something resembling the following:
$smbclient -L server
Added interface ip=192.168.236.86 bcast=192.168.236.255 nmask=255.255.255.0 Server time is Tue Apr 28 09:57:28 2002 Timezone is UTC-4.0 Password: Domain=[EXAMPLE] OS=[Unix] Server=[Samba 2.2.5] Sharename Type Comment --------- ---- ------- cdrom Disk CD-ROM cl Printer Color Printer 1 davecb Disk Home Directories Server Comment --------- ------- SERVER Samba 2.2.5 Workgroup Master --------- ------- EXAMPLE SERVER
-
If you didn’t get a Sharename list, the server is
not allowing you to browse any shares. This should not be the case if
you’ve tested any of the shares with Windows
Explorer or the net use command. If you
haven’t done thesmbclient
-L
localhost
-U%
test yet (see the earlier section, Section 12.2.5.2), do it now. An erroneous
guest account can prevent the shares from being seen. Also, check the
smb.conf file to make sure you do not have the
optionbrowsable
=
no
anywhere in it: we suggest using a minimal
smb.conf file (see the earlier section, Section 12.2.5.1). You need to have
browsable
enabled (which is the default) to see
the share. -
If you didn’t get a browse list, the server is not
providing information about the systems on the network. At least one
system on the net must support browse lists. Make sure you have
local
master
=
yes
in the
smb.conf file if you want Samba to be the local
master browser. -
If you got a browse list but didn’t get
/tmp, you probably have a
smb.conf problem. Go back to Section 12.2.4.5. -
If you didn’t get a workgroup list with your
workgroup name in it, it is possible that your workgroup is set
incorrectly in the smb.conf file. -
If you didn’t get a workgroup list at all, ensure
thatworkgroup
=
EXAMPLE
is present in the
smb.conf file. -
If you get nothing, try once more with the options
-I
ip_address
-n
netbios_name
-W
workgroup
-d3
with the NetBIOS and workgroup name in
uppercase. (The-d3
option sets the log /debugging
level to 3.) Then check the Samba logs for clues.
If you’re still getting nothing, you
shouldn’t have gotten this far; double back to at
least Section 12.2.3.1, or perhaps
Section 12.2.2.4. On the other hand:
-
If you get
SMBtconX
failed
.
ERRSRV--ERRaccess
, you aren’t
permitted access to the server. This normally means you have a
hosts
allow
option that
doesn’t include the server or a
hosts
deny
option that does. -
If you get
Bad
password
, you
presumably have one of the following:-
An incorrect
hosts
allow
or
hosts
deny
line -
An incorrect
invalid
users
or
valid
users
lin
-