- Настройка SNMP Traps в Linux
- Вливайтесь в общение
- Добавить комментарий Отменить ответ
- snmptrapd что это и с чем едят
- Snmp trap receiver linux
- Установка snmp, snmpd snmptrapd в Ubuntu, Debian, Linux Mint
- Настройка snmptrapd в Ubuntu, Debian, Linux Mint
- Настройка snmpd в Ubuntu, Debian, Linux Mint
- Snmp trap receiver linux
- Configure SNMP Traps
- Generate Event Notification Traps
- Define Access Credentials
- Define Trap Receivers
- SNMPv3 Trap and Inform Messages
- Source Traps from a Different Source IP Address
- Monitor Fans, Power Supplies, Temperature and Transformers
- Configure Link Up/Down Notifications
- Configure Free Memory Notifications
- Configure Processor Load Notifications
- Configure Disk Utilization Notifications
- Configure Authentication Notifications
- Monitor UCD-SNMP-MIB Tables
- Enable MIB to OID Translation
- Configure Incoming SNMP Traps
Настройка SNMP Traps в Linux
Приведу пример установки SNMP и ловли SNMP traps в Ubuntu Server.
В конфигурационном файле /etc/default/snmpd.conf изменяем значение параметра TRAPDRUN с no на yes и добавим -On в TRAPDOPTS=:
В конфигурационном файле /etc/snmp/snmptrapd.conf укажем комьюнити и что трапы необходимо передавать на snmptt:
В конфигурационном файле /etc/snmp/snmptt.ini укажем параметры:
Перезапустим snmpd и snmptt чтобы применить изменения:
Проверим запустились ли snmpd(udp 161) и snmptrapd(udp 162):
Можно временно остановить snmpd и запустить его вручную чтобы посмотреть в реальном времени какие SNMP traps приходят на сервер:
Если в системе используется iptables, то разрешим указанной ниже командой прием udp пакетов на порт 162 и сохраним добавленное правило чтобы оно не сбросилось после перезапуска системы:
Если все правильно настроили, то SNMP traps должны записываться в директории /var/log/snmptt/.
Вливайтесь в общение
Добавить комментарий Отменить ответ
Доброго времени суток. пытаюсь настроить по вашему мануалу. при запуске snmptt не стартует и выдает ошибку
Can’t use an undefined value as a symbol reference at /usr/share/perl5/Config/IniFiles.pm line 817, line 264.
Добрый день.
Укажите в файле конфигурации unknown_trap_log_enable = 1 чтобы записывались неизвестные трапы, проанализируйте их, так как изначально пишутся только известные прописанные в файле /etc/snmp/snmptt.conf
Добрый день.
После попытки запустить snmptrapd -f -L o
Получаю:
bash: /usr/sbin/snmptrapd: Нет такого файла или каталога
Решил, что Вы просто забыли указать snmptrapd в apt-get install
Проинсталлировал.
ручной запуск snmptrapd -f -L o работает и выводить в консоль принятые трапы
Однако при запуске демона и попытке отправить трап, каталог /var/log/snmptt пуст
Подскажите, что я делаю неправильно?
Источник
snmptrapd что это и с чем едят
Доброго времени суток . Не кидайте помидоры , за необразованность , изучаю просторы гугла , но пока без особых успехов . На виртуалке стоит 18 версии убунту . Установленны пакеты snmp snmpwalk snmptrapd и тп (ну вроде все нужные стоят ) . Задача понять как работает snmptrapd с примером работы . А именно научится ловить трапы без шифрации по 1 или 2 версии snmp . ловить трапы акулой я научился . а вот как с snmptrapd , ничего не найду и не пойму , либо все очевидно и под носом . помогите пожалуйста , как отправить самому себе трап по первой\второй версии snmp и самому же его поймать при помощи snmptrapd .
ну там рассказывает , хоть и очень грубо , как отправить трапу , а как поймать трапу ?
snmptrapd — Receive and log SNMP trap messages.
Твои вопросы странные, я не понимаю в чём у тебя проблема. Покажи что ты делаешь и что не получается.
мне нужно поймать при помощи snmptrapd трапу , которую я сам себе отправляю . в том то и дело что я ничего не делаю . я не понимаю как это сделать и прошу показать на пальцах . вполне возможно что мы говорим «на разных языках» и я ожидаю чего то невероятного ,а на самом деле все просто .
Чтобы с помощью программы что-то сделать, её нужно запустить и по-моему это очевидно.
Если ты откроешь man snmptrapd там будет написано как сделать красиво и даже есть секция examples
извиняюсь за свою тупость( и не сообразительность получается я прописываю sudo snmptrap -c public -v 2c 192.0.2.1 «» 1.3.3.3.3.3.3.3 1.2.2.2.2.2.2 s «HEFUIGF» и дальше писать sudo snmptrapd -Le -F «Получен трап %W %w.%q\n» ?? если так то вот что мне выводит консоль NET-SNMP version 5.7.3 AgentX subagent connected registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! registering pdu failed: 263! Warning: no access control information configured. (Config search path: /etc/snmp:/usr/share/snmp:/usr/lib/x86_64-linux-gnu/snmp:/home/itachi/.snmp) This receiver will NOT accept any incoming notifications. couldn’t open udp:162 – errno 98 («Address already in use») вы говорили что нужно запустить snmptrapd ,а как это делается ?
Внимание: прочитайте описание разметки Markdown или LORCODE.
Warning: no access control information configured.
Источник
Snmp trap receiver linux
Расскажу немно о пратоколе SNMP и основах работы с трапами (TRAP) на хостах под управление ОС Linux Mint, Ubuntu, Debian и.п. Рассмотрим процесс установки и настройки необходимых утилит и демонов, таких как, snmp, snmpd и snmptrapd.
Протокол SNMP используется для удаленного мониторинга и изменения настроек различных сетевых железок, буть то сервера, коммутаторы или маршрутизаторы.
Установка snmp, snmpd snmptrapd в Ubuntu, Debian, Linux Mint
Установим 3 пакета:
1. Пакет snmp включает в себя базавый набор библиотек и утилит необходимых для работы и отладки (например утилиту snmpwalk).
2. Демон snmpd необходим для управления и получения данных с нашего хоста по протоколу snmp.
3. Демон snmptrapd необходим для получения трапов от хостов.
Настройка snmptrapd в Ubuntu, Debian, Linux Mint
Файл настроек демона snmptrapd находиться в файле «/etc/snmp/snmptrapd.conf».
1. Первым делом устанавливаем community, для этого правим файл настроек «/etc/snmp/snmptrapd.conf». В большинстве случаев в качестве community устанавливаем public, но это необязательно, можете поставить какой-нибудь свой.
2. Далее включаем опцию на автоматический запуск snmptrapd в файле настроек «/etc/default/snmptrapd».
3. Перезапускаем snmptrapd.
4. Проверяем слушет наш демон 162-q порт.
5. Для проверки запустим тестовый trap на себя (127.0.0.1), с помощю утилиты snmptrap.
Смотрим файл сислога «/var/log/syslog», должна появиться строка о получение trap-а. Для просмотра syslog-а воспользуемся утилитой tail.
Видно что хост получил трап о чем свидетельствует запись в сислоге. Также проверим приходят ли трапы с удаленных хостов.
где 192.168.2.100 -ip адрес хоста на который отправляем трап.
Смотрим еще раз последнюю строку файла сислога «/var/log/syslog», должна появиться строка о получение trap-а с удалленого хоста.
Настройка snmpd в Ubuntu, Debian, Linux Mint
Файла настроек демона snmpd находиться в «/etc/snmp/snmpd.conf». После установки snmpd, по умолчанию, он должен работать на localhost-е.
1. Проверка работы snmpd с помощю утилиты snmpwalk.
Видно что по snmp отдаються данные с localhost.
Если вам надо опрашивать ваш host с другого адреса (например с удаленного компа) или порта (нестандартного порта), то надо изменить в файле настроек «/etc/snmp/snmpd.conf» строку.
где 192.168.1.100 — ip адрес вашего хоста, 162 — порт на хосте.
2. Изменение параметров «sysLocation» и «sysContact», для более легкой идентификации трапа.
3. Изменение дефолтного значения community.
По умолчанию в качестве community установлено public, это значение можно изменить в файле настроек «/etc/snmp/snmpd.conf».
где «private» — новое значение community. Параметры «default -V systemonly» являються необязательными, я рекомендую их оставить, т.к. без них, хост будет отдавать по snmp огромное количество всякой ненужной информации.
4. Перезапускаем демон snmpd.
Вот и все. Я постарался кратко рассказать о первоначальной настройки демонов snmpd и snmptrapd. Комментируем, подписываемся ну и всем пока:)
1″ :pagination=»pagination» :callback=»loadData» :options=»paginationOptions»>
Источник
Snmp trap receiver linux
SNMP trap collector with mysql database
SNMP Trap receiver (former EventDB) on RedHat
Install snmp package:
now we have to decide if Variant 1 or 2 (2 is preferred because of translated traps)
Creating just a normal trap database
Now, we need to create the database the traps will be stored in, as well as the database user we will use when logging traps.
Create the database we will log traps to:
Create the schema we will enter data into.
A database schema is the actual structure we write data to, including the tables. Consider it the ‘shape’ and ‘function’ of the database. The file describing the database schema is, as far as I can tell, not installed with snmpd. But it is present in the net-snmp source code distribution.
I reproduced it below.
Copy and paste this at the MariaDB prompt:
So you can send traps to the database using:
VARIANT 2: (PREFERED)
Database with trap translator: (PREFERED)
Install necessary packages:
(no install package in redhat repository)
Add the service using chkconfig:
Configure the service to start at runlevel 2345:
To manually start snmptt, use:
configure the snmptt.ini (see part Konfigurationen below)
We use a additional script /etc/sysconfig/snmptrapd to configure the start process of the snmptrap daemon.
SNMPTRAPD_PID=/var/run/snmptrapd.pid SNMPTRAPD_OPTS=»-On» SNMPTRAPD_CONFIG=»/etc/snmp/snmptrapd.conf» umask 002 OPTIONS=»-On -Lsd» umask 002
Important: We have to set the umask. The traps are stored from the snmptrapd as owner root and with gid icinga to the spool directory /var/spool/snmptt. The snmptt will run as user snmptt and the process have to be able to delete the traps are spooled.
Before we could start snmptrapd, we have to write the real configfile of snmptrapd to */etc/snmp/snmptrapd.conf. (later described again!)
Configuring the Database
create database eventdb;
grant all privileges on eventdb.* to ‘eventdb’@’localhost’ identified by ‘YOURPASSWORD’;
grant select on eventdb.* to ‘eventdb_r’@’localhost’ identified by ‘YOURPASSWORD_r’;
##### For database scheme we use the scheme from eventdb
tar xvfz eventdb-2.0.6.tar.gz
mysql eventdb -pYOURPASSWORD eventdb
To configure SNMPTT for MySQL, modify the following variables in the snmptt.ini file.
Note: Sample values are defined in the default ini file. Defining mysql_dbi_table_unknown is optional.
The following MySQL script can create the database and table. Permissions etc should also be defined. Run ‘mysql’ as root and enter:
Note: To store the traptime as a real date/time (DATETIME data type), change ‘traptime VARCHAR(30),’ to ‘traptime DATETIME,’ and set date_time_format_sql in snmptt.ini to %Y-%m-%d %H:%M:%S.
Note: If you do not want the auto-incrementing id column, remove the ‘id INT. ‘ line.
Note: To store the traptime as a real date/time (DATETIME data type), change ‘traptime VARCHAR(30),’ to ‘traptime DATETIME,’ and set date_time_format_sql in snmptt.ini to %Y-%m-%d %H:%M:%S.
If logging of statistics to a SQL table is required, create the snmptt_statistics table using:
Now it’s time to convert some MIBS for the snmptt:
configure the snmptrapd.conf (see part Konfigurationen below)
If this error occurs install/update Scalar::List > 1.33
Источник
Configure SNMP Traps
SNMP traps are alert notification messages sent from SNMP agents to the SNMP manager. These messages are generated whenever any failure or fault occurs in a monitored device or service. An SNMPv3 inform is an acknowledged SNMPv3 trap.
You configure the following for SNMPv3 trap and inform messages:
- The trap destination IP address; the VRF name is optional.
- The authentication type and password. The encryption type and password are optional.
- The engine ID/username pair for the Cumulus Linux switch sending the traps. The inform keyword specifies an inform message where the SNMP agent waits for an acknowledgement. You can find this at the end of the /var/lib/snmp/snmpd.conf file labeled oldEngineID. Configure this same engine ID/username (with authentication and encryption passwords) for the trap daemon receiving the trap to validate the received trap.
Generate Event Notification Traps
The Net-SNMP agent provides a method to generate SNMP trap events using the Distributed Management (DisMan) Event MIB for various system events, including:
- Link up/down.
- Exceeding the temperature sensor threshold, CPU load, or memory threshold.
- Other SNMP MIBs.
To enable specific types of traps, create the following configurations in /etc/snmp/snmpd.conf .
Define Access Credentials
Although the traps are sent to an SNMPv2c receiver, the SNMPv3 username is still required to authorize the DisMan service. Starting with Net-SNMP 5.3, snmptrapd no longer accepts all traps by default. snmptrapd must be configured with authorized SNMPv1/v2c community strings and/or SNMPv3 users. Non-authorized traps/informs are dropped.
Follow the steps in Configure SNMP to define the username. You can refer to the snmptrapd.conf(5) manual page for more information.
You may need to install the snmptrapd Debian package before you can configure the username.
Define Trap Receivers
The following configuration defines the trap receiver IP address where SNMPv1 and SNMPv2c traps are sent. For SNMP versions 1 and 2c, you must set at least one SNMP trap destination IP address; multiple destinations can exist. Removing all settings disables SNMP traps. The default version is 2c, unless otherwise configured. You must include a VRF name with the IP address to force traps to be sent in a non-default VRF table.
These commands create the following configuration in the /etc/snmp/snmpd.conf file:
To define the IP address of the notification (or trap) receiver for either SNMPv1 traps or SNMPv2 traps, use the trapsink (for SNMPv1) trap2sink (for SNMPv2c). Specifying more than one sink directive generates multiple copies of each notification (in the appropriate formats). You must configure a trap server to receive and decode these trap messages (for example, snmptrapd ). You can configure the address of the trap receiver with a different protocol and port but this is most often left out. The defaults are to use the well-known UDP packets and port 162. For example to use the localhost as the trap receiver:
Edit the /etc/snmp/snmpd.conf file and configure the trap settings.
Restart the snmpd service to apply the changes.
SNMPv3 Trap and Inform Messages
The SNMP trap receiving daemon must have usernames, authentication passwords, and encryption passwords created with its own EngineID. You must configure this trap server EngineID in the switch snmpd daemon sending the trap and inform messages. You specify the level of authentication and encryption for SNMPv3 trap and inform messages with -l ( NoauthNoPriv, authNoPriv, or authPriv ).
For inform messages, the engine ID/username creates the username on the receiving trap daemon server. The trap receiver sends the response for the trap message using its own engine ID/username. In practice, the trap daemon generates the usernames with its own engine ID and after these are created, the SNMP server (or agent) needs to use these engine ID/usernames when configuring the inform messages so that they are correctly authenticated and the correct response is sent to the snmpd agent that sent it.
You can configure SNMPv3 trap and inform messages with the trapsess configuration command. Inform messages are traps that are acknowledged by the receiving trap daemon. You configure inform messages with the -Ci parameter. You must specify the EngineID of the receiving trap server with the -e field.
You can define multiple trap receivers and use the domain name instead of an IP address in the trap2sink directive.
Restart the snmpd service to apply the changes:
Source Traps from a Different Source IP Address
When client SNMP programs (such as snmpget , snmpwalk , or snmptrap ) are run from the command line, or when snmpd is configured to send a trap (based on snmpd.conf ), you can configure a clientaddr in snmpd.conf that allows the SNMP client programs or snmpd (for traps) to source requests from a different source IP address.
For more information about clientaddr , read the snmpd.conf man page.
snmptrap , snmpget , snmpwalk and snmpd itself must be able to bind to this address.
There is no NCLU command for this configuration.
Edit the /etc/snmp/snmpd.conf file and add the clientaddr option. In the following example, spine01 is used as the client (IP address 192.168.200.21).
Restart the snmpd service to apply the changes.
Monitor Fans, Power Supplies, Temperature and Transformers
An SNMP agent ( snmpd ) waits for incoming SNMP requests and responds to them. If no requests are received, an agent does not initiate any actions. However, various commands can configure snmpd to send traps based on preconfigured settings ( load , file , proc , disk , or swap commands), or customized monitor directives.
See the snmpd.conf man page for details on the monitor directive.
You can configure snmpd to monitor the operational status of either the Entity MIB or Entity-Sensor MIB by adding the monitor directive to the snmpd.conf file. Once you know the OID, you can determine the operational status — which can be a value of ok(1), unavailable(2) or nonoperational(3) — by adding a configuration like the following example to /etc/snmp/snmpd.conf and adjusting the values:
- Using the entPhySensorOperStatus integer:
- Using the OID name. You can use the OID name if the snmp-mibs-downloader package is installed (see below).
The entPhySensorOperStatus integer can be found by walking the entPhysicalName table.
To get all sensor information, run snmpwalk on the entPhysicalName table. For example:
Restart the snmpd service to apply the changes.
There is no NCLU command for monitoring hardware.
In earlier versions of Cumulus Linux, you could use the LM-SENSORS MIB to monitor temperature, but that MIB has been deprecated.
Configure Link Up/Down Notifications
The linkUpDownNotifications directive is used to configure link up/down notifications when the operational status of the link changes.
The default frequency for checking link up/down is 60 seconds. You can change the default frequency using the directly instead of the linkUpDownNotifications directive. See man snmpd.conf for details.
To enable notifications for interface link-up events to be sent to SNMP trap destinations every 15 seconds, run:
Similarly, to enable notifications for interface link-down events to be sent to SNMP trap destinations every 10 seconds, run:
Edit the /etc/snmp/snmpd.conf file and configure the trap settings.
To enable link up and link down trap notifications, add linkUpDownNotifications yes to the snmpd.conf file and provide a trap configuration. The following configuration enables the Event MIB tables to monitor the ifTable for network interfaces being taken up every 15 seconds or down every 10 seconds, and triggers a linkUp or linkDown notification as appropriate:
Restart the snmpd service to apply the changes.
Configure Free Memory Notifications
You can monitor free memory using the following directives. The example below generates a trap when free memory drops below 1,000,000KB. The free memory trap also includes the amount of total real memory:
Restart the snmpd service to apply the changes.
There is no NCLU command for monitoring free memory.
Configure Processor Load Notifications
To enable a trap when the CPU load average exceeds a configured threshold, run the following commands. You can only use integers or floating point numbers.
Edit the /etc/snmp/snmpd.conf file and configure the CPU load settings.
To monitor CPU load for 1, 5, or 15 minute intervals, use the load directive with the monitor directive. The following example generates a trap when the 1 minute interval reaches 12%, the 5 minute interval reaches 10%, or the 15 minute interval reaches 5%.
Restart the snmpd service to apply the changes.
Configure Disk Utilization Notifications
To monitor disk utilization for all disks, use the includeAllDisks directive together with the monitor directive. The example code below generates a trap when a disk is 99% full:
Restart the snmpd service to apply the changes.
There is no NCLU command for monitoring disk utilization.
Configure Authentication Notifications
To enable SNMP trap notifications to be sent for every SNMP authentication failure, run the following commands.
To generate authentication failure traps, use the authtrapenable directive:
Restart the snmpd service to apply the changes.
Monitor UCD-SNMP-MIB Tables
To configure the Event MIB tables to monitor the various UCD-SNMP-MIB tables for problems (as indicated by the appropriate xxErrFlag column objects) and send a trap, add defaultMonitors yes to the snmpd.conf file and provide a configuration. You must first download the snmp-mibs-downloader Debian package and comment out the mibs line from the /etc/snmp/snmpd.conf file (see below). Then add a configuration like the following example:
Restart the snmpd service to apply the changes.
Enable MIB to OID Translation
MIB names can be used instead of OIDs, which greatly improves the readability of the snmpd.conf file. You enable this by installing the snmp-mibs-downloader , which downloads SNMP MIBs to the switch prior to enabling traps.
Open /etc/apt/sources.list in a text editor.
Add the non-free repository, then save the file:
Update the switch:
Install the snmp-mibs-downloader :
Open the /etc/snmp/snmp.conf file to verify that the mibs : line is commented out:
Open the /etc/default/snmpd file to verify that the export MIBS= line is commented out:
After you confirm the configuration, remove or comment out the non-free repository in /etc/apt/sources.list .
Configure Incoming SNMP Traps
The Net-SNMP trap daemon configured in /etc/snmp/snmpd.conf receives SNMP traps. You configure how incoming traps are processed in the /etc/snmp/snmptrapd.conf file. Starting with Net-SNMP release 5.3, you must specify who is authorized to send traps and informs to the notification receiver (and what types of processing these are allowed to trigger). You can specify three processing types:
- log logs the details of the notification in a specified file to standard output (or stderr), or through syslog (or similar).
- execute passes the details of the trap to a specified handler program, including embedded Perl.
- net forwards the trap to another notification receiver.
Typically, you configure all three — log,execute,net — to cover any style of processing for a particular category of notification. But you can limit certain notification sources to selected processing only.
authCommunity TYPES COMMUNITY [SOURCE [OID | -v VIEW ]] authorizes traps and SNMPv2c INFORM requests with the specified community to trigger the types of processing listed. By default, this allows any notification using this community to be processed. You can use the SOURCE field to specify that the configuration only applies to notifications received from particular sources. For more information about specific configuration options within the file, look at the snmptrapd.conf(5) man page with the man 5 snmptrapd.conf command.
You may need to install the snmptrapd Debian package before you can configure incoming traps.
Источник