LinuxForum.Fans
Тема

Проблемы с SNMP Trap

Автор: Ravil 48 сообщений 8464 просмотров
#367146

Есть система CentOS 6.5. Установил и запустил сервисы snmpd, snmptrapd и snmptt (в дальнейшем мне это необходимо для nagios). Необходимо принимать trap. Я начал тестить, ловят ли snmptrapd и snmptt трапы (начал отправлять trap с другой системы). В логах snmptrapd.log все трапы появились, то есть сервис snmpdtrapd функционирует исправно. Но в логах snmptt.log ничего нет (если точнее, snmptt даже не создал этот файл).

text
Настройки файла snmptrapd.conf:
traphandler default /usr/sbin/snmptthandler
logoption f /var/log/snmptrap.log
disableAuthorization yes
text

Настройки файла snmptt.ini:
mode=daemon
net_snmp_perl_enable=1
spool_directory=/var/spool/snmptt/
use_trap_time=1
keep_unlogged_traps=1
stdout_enable=1
log_enable=1
log_file=/var/log/snmptt/snmptt.log
log_system_enable=1
log_system_file=/var/log/snmptt/snmpttsystem.log
unknown_trap_log_enable=1
unknown_trap_log_file=/var/log/snmptt/snmpttunknown.log

В чем может быть проблема?

#367254

В /var/spool/snmptt/ пусто?

#367298
Macumazan написал:
В /var/spool/snmptt/ пусто?

Да, пусто

#369214
Macumazan написал:
В /var/spool/snmptt/ пусто?

Вот мой конфиг snmptt.ini:

text

snmptt_system_name =
#mode = standalone
mode = daemon
multiple_event = 1
dns_enable = 0
strip_domain = 0
strip_domain_list = <<END
domain.com
END
resolve_value_ip_addresses = 0
net_snmp_perl_enable = 1
net_snmp_perl_cache_enable = 1
net_snmp_perl_best_guess = 0
translate_log_trap_oid = 0
translate_value_oids = 1
translate_enterprise_oid_format = 1
translate_trap_oid_format = 1
translate_varname_oid_format = 1
translate_integers = 1
mibs_environment = ALL
wildcard_expansion_separator = " "
allow_unsafe_regex = 0
remove_backslash_from_quotes = 0
dynamic_nodes = 0
description_mode = 0
description_clean = 1
threads_enable = 0
threads_max = 10
date_time_format = %H-%M-%S %Y:%m:%d

[DaemonMode] daemon_fork = 1 daemon_uid = snmptt pid_file = /var/run/snmptt.pid spool_directory = /var/spool/snmptt/ sleep = 5 use_trap_time = 1 keep_unlogged_traps = 1 duplicate_trap_window = 0

[Logging] stdout_enable = 1 log_enable = 1 log_file = /var/log/snmptt/snmptt.log log_system_enable = 1 log_system_file = /var/log/snmptt/snmpttsystem.log unknown_trap_log_enable = 1 unknown_trap_log_file = /var/log/snmptt/snmpttunknown.log statistics_interval = 0 syslog_enable = 1 syslog_facility = local0 syslog_level_debug = <<END END syslog_level_info = <<END END syslog_level_notice = <<END END syslog_level_warning = <<END END syslog_level_err = <<END END syslog_level_crit = <<END END syslog_level_alert = <<END END syslog_level = warning syslog_system_enable = 1 syslog_system_facility = local0 syslog_system_level = warning

[Exec] exec_enable = 1 pre_exec_enable = 1 unknown_trap_exec = unknown_trap_exec_format = exec_escape = 1

[Debugging] DEBUGGING = 2 DEBUGGING_FILE = /var/log/snmptt/snmpttdebug.log DEBUGGING_FILE_HANDLER =

[TrapFiles] snmptt_conf_files = <<END END

text

[root@localhost ~]# ps -e | grep snmptt
 1015 ?        00:00:00 snmptt
 1016 ?        00:00:00 snmptt

Это нормально, что запущено два процесса snmptt?

Из всех файлов создались только /var/log/snmptt/snmpttsystem.log и /var/log/snmptt/snmpttdebug.log. MIB баз у меня пока что нет, но и без них ведь все trap-ы, которые приходят, должны логироваться в файл snmpttunknown.log, но и этого не происходит. Я уже не знаю, что делать

#369233

Да, у меня тоже 2 процесса.
В момент рестарта snmptt есть что-либо в syslog?

#369243
Macumazan написал:
Да, у меня тоже 2 процесса.
В момент рестарта snmptt есть что-либо в syslog?

Вот какие записи появляются в /var/log/snmptt/snmpttsystem.log в момент рестарта snmptt:

text

2014-02-13 04:52:15 SNMPTT v1.4 shutdown
2014-02-13 04:52:15 Total traps received=0,Total traps translated=0,Total traps ignored=0,Total unknown traps=0
2014-02-13 04:52:19 SNMPTT v1.4 started
2014-02-13 04:52:19 Loading /etc/snmp/snmptt.conf
2014-02-13 04:52:19 Finished loading 64 lines from /etc/snmp/snmptt.conf
2014-02-13 04:52:19 Changing to UID: snmptt (501)
#369244

А snmptt.conf как выглядит?

#369245
Macumazan написал:
А snmptt.conf как выглядит?

snmptt.conf у меня из репозиториев snmptt_1.4, которые я скачивал. Дополнительные MIB я пока что не качал и не транслировал.
Вот на данный момент, как он выглядит:

text

#
#
#
EVENT coldStart .1.3.6.1.6.3.1.1.5.1 "Status Events" Normal
FORMAT Device reinitialized (coldStart)
#EXEC qpage -f TRAP notifygroup1 "Device reinitialized (coldStart)"
SDESC
A coldStart trap signifies that the SNMPv2 entity, acting
in an agent role, is reinitializing itself and that its
configuration may have been altered.
EDESC
#
#
#
EVENT warmStart .1.3.6.1.6.3.1.1.5.2 "Status Events" Normal
FORMAT Device reinitialized (warmStart)
#EXEC qpage -f TRAP notifygroup1 "Device reinitialized (warmStart)"
SDESC
A warmStart trap signifies that the SNMPv2 entity, acting
in an agent role, is reinitializing itself such that its
configuration is unaltered.
EDESC
#
#
#
EVENT linkDown .1.3.6.1.6.3.1.1.5.3 "Status Events" Normal
FORMAT Link down on interface $1.  Admin state: $2.  Operational state: $3
#EXEC qpage -f TRAP notifygroup1 "Link down on interface $1.  Admin state: $2. $
SDESC
A linkDown trap signifies that the SNMP entity, acting in
an agent role, has detected that the ifOperStatus object for
one of its communication links is about to enter the down
state from some other state (but not from the notPresent
state).  This other state is indicated by the included valueof ifOperStatus.
EDESC
#
#
#
EVENT linkUp .1.3.6.1.6.3.1.1.5.4 "Status Events" Normal
FORMAT Link up on interface $1.  Admin state: $2.  Operational state: $3
#EXEC qpage -f TRAP notifygroup1 "Link up on interface $1.  Admin state: $2.  O$
SDESC
A linkUp trap signifies that the SNMP entity, acting in an
agent role, has detected that the ifOperStatus object for
one of its communication links left the down state and
transitioned into some other state (but not into the
notPresent state).  This other state is indicated by the
included value of ifOperStatus.
EDESC
#
#
#
EVENT authenticationFailure .1.3.6.1.6.3.1.1.5.5 "Status Events" Normal
FORMAT SNMP athentication failure
#EXEC qpage -f TRAP notifygroup1 "SNMP authentication failure"
SDESC
An authenticationFailure trap signifies that the SNMPv2
entity, acting in an agent role, has received a protocol
message that is not properly authenticated.  While all
implementations of the SNMPv2 must be capable of generating
this trap, the snmpEnableAuthenTraps object indicates
whether this trap will be generated.
EDESC
#369255

Попробуй фильтр

text
EVENT All .* "category" NORMAL
EXEC echo test complete >> /tmp/testtrap.log
SDESC
EDESC

за место всех остальных. Если он перехватит трап, то сработает EXEC.


Еще в ini можно добавить

text
[Debugging]
DEBUGGING = 2
DEBUGGING_FILE = /var/log/snmptt/snmptt.debug
DEBUGGING_FILE_HANDLER = /var/log/snmptt/snmptthandler.debug

и посмотреть, что там происходит.

#369338

Попробовал такой фильтр - ничего не меняется. Файл /tmp/testtrap.log я даже сам создал, но в него ничего не пишется.
Команду trap использовал так:

text

snmptrap -v 1 -c public 192.168.0.124 '1.2.3.4.5.6' '192.168.0.124' 6 99 '' .1.3.6.1.6.3.1.1.5.5 s "testing"

В snmpttdebug.log каждые 5 секунд пишет следующее:

text

Sleeping for 5 seconds

Total traps received: 0 Total traps translated: 0 Total traps ignored: 0 Total unknown traps: 0

Sleeping for 5 seconds

Total traps received: 0 Total traps translated: 0 Total traps ignored: 0 Total unknown traps: 0

В snmpttsystem.log каждые 5 секунд пишет:

text

09-24-41 2014:02:27 Total traps received=0,Total traps translated=0,Total traps ignored=0,Total unknown traps=0

Так чувство, будто до snmptt трапы вообще не доходят, либо snmptrapd их ему не передает, сервис snmptt то запущен

#369339

Можешь посмотреть, у тебя владельцы папок такие же?

text

[root@localhost snmp]# ll /var/log/snmptt/
total 3484
-rwxrwxr--. 1 snmptt snmptt 2182358 Feb 27 09:33 snmpttdebug.log
-rwxrwxr--. 1 snmptt snmptt 1374630 Feb 27 09:29 snmpttsystem.log
[root@localhost snmp]# ll -d /var/log/snmptt/
drwxrwxr-x. 2 snmptt snmptt 4096 Feb 25 09:21 /var/log/snmptt/
[root@localhost snmp]# ll /var/spool/snmptt
total 0
[root@localhost snmp]# ll -d /var/spool/snmptt
drwxrwxr-x. 2 snmptt snmptt 4096 Feb 18 09:59 /var/spool/snmptt
#369341

Macumazan,
Можешь скинуть свой код файла /usr/sbin/snmptthandler? Я думаю, проблема в нём.

#369359

В /var/spool/snmptt вообще никакие записи не появляются. Я скачал MIB базу для IBM x3650, с помощью snmpttconvertmib преобразовал в snmptt-imm.conf, прописал этот путь в snmptt.ini. На сервере специально при аутентификации ввел неправильный пароль и trap полетел на сервер мониторинга. В логах snmptrapd.conf трап увидел, но директории /var/spool/snmptt и /var/log/snmptt/ остались неизменны.

#369398

Да , владелец верный.
Еще момент: останови сервис snmptt и отправь трап. Поавился ли файл в /var/spool/snmptt?

text
cat /usr/sbin/snmptthandler 

#!/usr/bin/perl # # SNMPTTHANDLER v1.2 # # Copyright 2002-2007 Alex Burger # alex_b@users.sourceforge.net # 8/26/2002 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ############################################################################## # # http://www.sourceforge.net/projects/snmptt # # This script is a snmp trap handler for use with the NET-SNMP / UCD-SNMP # snmptrapd program and SNMPTT. # # The script is called by defining a 'traphandle' in snmptrapd.conf. # For example: # # traphandle default /sbin/snmptthandler # # SNMPTRAPD feeds details about the trap to the launched program's standard # input in the following format (see snmptrapd.conf man page for a complete # descriptipon) # # HOSTNAME: The name of the host in question that sent the trap # IPADDRESS: The IP address of the host that sent the trap # VARBINDS: A list of variable bindings that describe the trap and # the variables enclosed in it. # # SNMPTTHANDLER dumps the received traps into a directory to be processed # by the SNMPTT daemon. # ############################################################################## use strict;

# Process command line arguments

use Getopt::Long; use Time::HiRes qw(gettimeofday);

my $version = ''; my $debug = ''; my $help = ''; my $ini = ''; my $debugfile = '';

GetOptions ('version' => \$version, 'debug:i' => \$debug, 'debugfile=s' => \$debugfile, 'help' => \$help, 'ini=s' => \$ini); if ($version) { &showversion; exit(0); }

if ($help) { my $USAGE = qq/Usage: snmptthandler [<options>] Options: --debug=n Set debug level (1 or 2) --debugfile=filename Set debug output file --help Display this message --ini=filename Set configuration file to load --version Display author and version information /;

&showversion; print $USAGE;

exit(0); }

my $DEBUGGING; my $DEBUGGING_FILE; my $debugcmdline; my $debugfilecmdline;

if ($debug >= 1) { $DEBUGGING = 1; $debugcmdline = 1 }

if ($debugfile ne '') { $DEBUGGING_FILE = $debugfile; # commandline overpowers snmptt script $debugfilecmdline = 1; }

############################################################################## # # Load config file start # # For Linux / Unix, try /etc/snmp/snmptt.ini first, /etc/snmptt.ini second. # # For Windows, try %SystemRoot%\snmptt.ini only. # my $configfile;

if ($ini ne '') { $configfile = $ini; } else { if ($^O ne "MSWin32") { $configfile = '/etc/snmp/snmptt.ini'; if( open( CONFIG, '/etc/snmp/snmptt.ini' ) ) { $configfile = '/etc/snmp/snmptt.ini'; close CONFIG; } elsif ( open( CONFIG, '/etc/snmptt.ini' ) ) { $configfile = '/etc/snmptt.ini'; close CONFIG; } } else { $configfile = $ENV{'SystemRoot'}."\\snmptt.ini"; } }

my $spool_directory; &loadsnmpttini;

############################################################################## # Pull in passed SNMP info from snmptrapd via STDIN and place in the array @tempvar

# Create file in spool directory based on current time my ($s, $usec) = gettimeofday;

# Pad the numbers with 0's to make sure they are all the same length. Sometimes the # usec is shorter than 6. my $s_pad = sprintf("%09d",$s); my $usec_pad = sprintf("%06d",$usec);

if ($DEBUGGING >= 1) { if ($DEBUGGING_FILE ne '') { open DEBUGFILE, ">>$DEBUGGING_FILE" or warn "Could not open debug output file ($!)";

select DEBUGFILE; # Change default output to debug file }

# Print out time print "SNMPTTHANDLER started: ",scalar(localtime),"\n\n"; print "s = $s, usec = $usec\n"; print "s_pad = $s_pad, usec_pad = $usec_pad\n\n"; print "Data received:\n\n"; }

my $spoolfile = $spool_directory.'#snmptt-trap-'.$s_pad.$usec_pad;

unless (open SPOOL, ">$spoolfile") { if ($DEBUGGING >= 1) { print "Could not write to file file $spoolfile! Trap will be lost!\n"; } die "Could not write to file $spoolfile! Trap will be lost!\n"; }

print SPOOL time()."\n";

while (defined(my $line = <>)) { print SPOOL $line;

if ($DEBUGGING >= 1) { # Print out item passed from snmptrapd print $line."\n"; }

}

##############################################################################

sub showversion { printf "\nSNMPTTHANDLER v1.2\n"; printf "(c) 2002-2007 Alex Burger\n\n"; }

##############################################################################

sub loadsnmpttini {

############################################################################## # # Load config file start # use Config::IniFiles; my $cfg;

# ##############################################################################

if( open( CONFIG, $configfile ) ) { close CONFIG; $cfg = new Config::IniFiles( -file => $configfile); } else { if ($DEBUGGING >= 1) { print "Config file ($configfile) could not be loaded\n"; } warn "Config file ($configfile) could not be loaded\n"; exit(1); }

if (! $cfg) { if ($DEBUGGING >= 1) { print "Error in config file - please check the syntax in the config file\n"; } exit(1); }

# DaemonMode $spool_directory = $cfg->val('DaemonMode', 'spool_directory');

# Debugging if ($debugcmdline == 0) { $DEBUGGING = $cfg->val('Debugging', 'DEBUGGING'); } if ($debugfilecmdline == 0) { $DEBUGGING_FILE = $cfg->val('Debugging', 'DEBUGGING_FILE_HANDLER'); }

$cfg->Delete;

# # Defaults Start # if (! defined ($spool_directory)) { $spool_directory = ''} ; if (! defined ($DEBUGGING)) { $DEBUGGING = 0} ; if (! defined ($DEBUGGING_FILE)) { $DEBUGGING_FILE = ''} ; # # Defaults End #

# print "Config file loaded\n";

# # Load config file end # ############################################################################## }

#369424
"Macumazan" написал:
Еще момент: останови сервис snmptt и отправь трап. Поавился ли файл в /var/spool/snmptt?

Нет, ничего не появилось. Файл snmptt.ini у меня такой же, только версии 1.4.

#369557

Всё заработало!!! *THUMBSUP* *OK*
Проблема была, как я и думал, с файлом snmptthandler. Я попытался его выполнить и увидел:

text

[root@localhost ~]# /usr/sbin/snmptthandler
Can't locate Time/HiRes.pm in @INC (@INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at /usr/sbin/snmptthandler line 53.
BEGIN failed--compilation aborted at /usr/sbin/snmptthandler line 53.

После установки пакета perl-Time-HiRes всё заработало!!! Спасибо за помощь :)

#369559

Macumazan,
Хм...меня кое что смущает. Я в snmptt.ini настроил запись всех логов в БД (БД соответственно создал заранее). Отключил все логи, кроме snmpttsystem.log и snmpttdebug.log В snmpttdebug.log сейчас пишется:

text

Processing file: #snmptt-trap-1393551040817194
Reading trap.  Current time: Fri Feb 28 11:12:37 2014
  Invalid trap file.  Expected a serial time on the first line but got nothing
  Error processing trap file #snmptt-trap-1393551040817194.  Skipping...
Sleeping for 5 seconds

Что это значит?
Я смотрю на нагиос щас и там всё работает. Если на IBM x3650 кто-то логинится, на веб-морде нагиоса сразу же показывается соответствующий трап. Но записи в snmpttdebug меня всё равно смущают.

#369582

Надо посмотреть , что в #snmptt-trap-1393551040817194 или в любых других.

#369583
Ravil написал:
Всё заработало!!! *THUMBSUP* *OK*
Проблема была, как я и думал, с файлом snmptthandler. Я попытался его выполнить и увидел:
text

[root@localhost ~]# /usr/sbin/snmptthandler
Can't locate Time/HiRes.pm in @INC (@INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at /usr/sbin/snmptthandler line 53.
BEGIN failed--compilation aborted at /usr/sbin/snmptthandler line 53.

После установки пакета perl-Time-HiRes всё заработало!!! Спасибо за помощь :)

Кстати, а пакет из репозитория ставился? Если да, то можно смело писать в багзиллу)

#369595
Macumazan написал:
Надо посмотреть , что в #snmptt-trap-1393551040817194 или в любых других.

В /var/spool/snmptt создан все один файл: #snmptt-trap-1393551040817194
Каким образом создаются файлы? Для каждого трапа свой файл? Или как? я поймал с IBM x3650 уже 4 трапа, связанных с аутентификацией, но файл создан всего один. А сам файл пустой o_O

Войдите или зарегистрируйтесь, чтобы ответить.