- How to send snmp trap from linux
- Установка snmp, snmpd snmptrapd в Ubuntu, Debian, Linux Mint
- Настройка snmptrapd в Ubuntu, Debian, Linux Mint
- Настройка snmpd в Ubuntu, Debian, Linux Mint
- Настройка SNMP Traps в Linux
- Вливайтесь в общение
- Добавить комментарий Отменить ответ
- SNMP Trap — How To Send A Test Trap
- Overview
- Uptime
- SNMP v2 Trap
- SNMP v3 Trap
- SNMP Trap Definition
- Trap vs Inform
- SNMP Trap Configuration
- Final Thoughts
- TUT:snmptrap
- Contents
- Trap Definitions
- SMIv1 Traps
- SMIv2 Notifications
- Variables
- Traps vs Notifications
- SNMP Traps
- SNMPv1 Traps
- SNMPv2 Traps
- SNMPv2 Informs
- SNMPv3 Notifications
- Agent Traps
- Tutorial Sections
- About the SNMP Protocol
- Net-SNMP Command Line Applications
- Application Configuration
- Net-SNMP Daemons
- Coding Tutorials
- Debugging SNMP Applications and Agents
How to send snmp trap from 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 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 пуст
Подскажите, что я делаю неправильно?
Источник
SNMP Trap — How To Send A Test Trap
Overview
This article shows you several methods of sending a trap to your Nagios server to test SNMP Trap functionality.
Sometimes when troubleshooting an SNMP Trap issue, it can be very helpful to remove the actual device that could be causing problems and use the snmptrap command instead. This troubleshooting method will confirm if your Nagios server is correctly receiving SNMP Traps and is configured correctly.
You will be executing the command on the Nagios host itself, this is why you see localhost in the commands below.
Uptime
When you send a trap, it must of course conform to a set of standards. The options are explained in each section below however there is one option that is common and needs explaining, uptime.
Every trap needs an uptime value. Uptime is how long the system has been running since boot. Sometimes this is the operating system, other devices might use the SNMP engine uptime. Regardless, a value will be sent.
So what value should you type in the commands below? Oddly enough, simply supplying no value by using two single quotes » will instruct the command to obtain the value from the operating system you are executing this on.
For those who dig deeper and look at the spooled trap before it’s processed will want to understand what type of format it is. Here is an example:
This equates to 36 days, 2 hours, 40 minutes and 51.67 seconds.
The key point to this section is that you now know why the commands below have two single quotes » for the uptime value.
SNMP v2 Trap
The command below takes the form of:
Shortening the MIB:
Using OID’s instead of MIB:
The commands above required the following settings in /etc/snmp/snmptrapd.conf
SNMP v3 Trap
The command below takes the form of:
Shortening the MIB:
Using OID’s instead of MIB:
The commands above required the following settings in /etc/snmp/snmptrapd.conf
SNMP Trap Definition
The following trap definition can be placed in /etc/snmp/snmptt.conf which will allow the test traps sent above to be passed through to Nagios:
Trap vs Inform
TRAP
A TRAP is a SNMP message sent from one application to another (which is typically on a remote host). Their purpose is merely to notify the other application that something has happened, has been noticed, etc. The big problem with TRAPs is that they’re unacknowledged so you don’t actually know if the remote application received your oh-so-important message to it.
INFORM
SNMPv2 PDUs fixed this by introducing the notion of an INFORM, which is nothing more than an acknowledged TRAP. IE, when the remote application receives the INFORM it sends back a «I got it» message. This is nice because then the person sending the traps can keep trying until the trap gets through.
All of the commands above can be changed from snmptrap to snmpinform which will allow you to send a test inform.
SNMP Trap Configuration
More detailed information on configuring your server to accept SNMP TRAP’s can be found in the following KB articles:
Final Thoughts
For any support related questions please visit the Nagios Support Forums at:
Источник
TUT:snmptrap
Most SNMP traffic is sent from a management station to a network entity, in order to find out about that system or adjust its configuration in some way. Notifications (Traps and Informs) can be used by a network entity to signal abnormal conditions to a management station.
Typically, such a notification would normally be generated by an SNMP agent, but this tutorial will concentrate on the snmptrap command, which can also be used to generate such traps.
Contents
Trap Definitions
There are two ways of defining a notification — one used in SMIv1 MIBs and one used in SMIv2 MIBs. The two styles are basically equivalent, and it is possible to convert between the two. In particular, it is perfectly valid to send an SMIv2-defined notification as an SNMPv1 trap, or an SMIv1-defined trap as an SNMPv2c (or SNMPv3) notification.
SMIv1 Traps
A trap is defined in an SMIv1 MIB file using the TRAP-TYPE macro, as in the following example:
Note that the trap is identified by two values — the ENTERPRISE-oid (.1.3.6.1.4.1.2021.13.990 which is TRAP-TEST-MIB::demotraps) and the specific-trap value of the TRAP-TYPE macro (17)
SMIv2 Notifications
A notification is defined in an SMIv2 MIB file using the NOTIFICATION-TYPE macro, as in the following example:
Note that this defines a single OID which will uniquely identify the notification.
Variables
Both SMIv1 and SMIv2 definitions can specify additional information that should be included within the trap. The name of the clause is different between the two definitions (VARIABLES vs OBJECTS), but the meaning is the same — the notification should include a varbind (OID and value) for each object listed, in the order that they appear.
[ ] Object vs Instance
Traps vs Notifications
Strictly speaking, we should probably refer to all such MIB definitions as «notifications» — with the term «trap» being reserved for the (unacknowledged) SNMP request used to transport the relevant information. But people do tend to use the two terms interchangeably (as has been the case in this tutorial as well!)
SNMP Traps
OK — so that describes how notifications are defined in a MIB file. How are they represented as SNMP requests?
SNMPv1 Traps
Unsurprisingly, the format of a trap request follows the format of the corresponding SMI definition fairly closely. So an SNMPv1 trap should contain two values — the enterprise OID and the value of the trap itself, right?
Wrong! It actually contains three elements — an enterprise-OID and two trap values — a «generic-trap» field and a «specific-trap» field. For traps defined in a custom MIB file (specific traps), the «generic-trap» field will always have the value 6, and the «specific-trap» field will have the value of the TRAP-TYPE macro. So the combined OID, identifying the trap will be
For predefined (generic traps), «generic-trap» field will have a number identifying the trap, «specific-trap» value is irrelevant. Combined OID will be
In fact, the SNMPv1 trap request actually contains five values — these three plus the «agent» field (IP address of the system generating the trap, useful if you have more than one network interface), and the sysUpTime of the generating application.
The snmptrap command will use sensible defaults for these two fields, so it’s really just necessary to provide the enterprise-OID and the two trap values, plus the payload of the trap itself [OID, type, value]:
Note that this command also includes an (OID,type,value) triple for the varbinds listed in the VARIABLES clause (in the same way as with the snmpset command).
In case you don’t have UCD-TRAP-TEST-MIB module defined (default installation on Redhat and Suse), you may try NET-SNMP-EXAMPLES-MIB module instead:
SNMPv2 Traps
SNMPv2 simplified the format of a notification request, consolidating everything within the varbind list, rather than having separate header fields just for Trap requests. So the first two varbinds of an SNMPv2 notification will be sysUpTime.0 following by snmpTrapOID.0 . The value of this second varbind is the OID identifying the trap being sent.
The snmptrap command will insert a sensible value for the sysUpTime varbind, so it’s really just necessary to provide the trap OID (plus any additional varbinds from the OBJECTS clause):
In case you don’t have UCD-TRAP-TEST-MIB module defined (default installation on Redhat and Suse), you may try NET-SNMP-EXAMPLES-MIB module instead:
SNMPv2 Informs
[ ] Similar to Traps, but acknowledged — i.e. resend if no response
SNMPv3 Notifications
[ ] Same as SNMPv2, but v3 admin
Agent Traps
The agent is able to generate a few traps by itself. When starting up, it will generate a SNMPv2-MIB::coldStart trap, and when shutting down a UCD-SNMP-MIB::ucdShutDown.
These traps are sent to managers specified in the snmpd.conf file, using the trapsink or trap2sink directive (SNMPv1 and SNMPv2 trap respectively)
In addition, the agent is able to send authentication failure traps to the same hosts as above, controlled by the authtrapenable directive in snmpd.conf, or by setting the SNMPv2-MIB::snmpEnableAuthenTraps variable
To perform various tasks when notifications arrive at the Net-SNMP snmptrapd notification receiver, please see the page on TUT:Configuring snmptrapd
Tutorial Sections
About the SNMP Protocol
These tutorial links talk about SNMP generically and how the protocol itself works. They are good introductory reading material and the concepts are important to understand before diving into the later tutorials about Net-SNMP itself.
- How SNMP Works: About the protocol itself (GETs, GETNEXTs, etc)
- What data is in SNMP: All about SNMP Management Information Bases (MIBs)
- Securing SNMP: How to use the SNMP protocol securely
Net-SNMP Command Line Applications
These tutorial pages discuss the command line tools provided in the Net-SNMP suite of tools. Nearly all the example commands in these tutorials works if you try it yourself, as they’re all examples that talk to our online Net-SNMP test agent. Given them a shot!
- snmptranslate: learning about the MIB tree.
- snmpget: retrieving data from a host.
- snmpgetnext: retrieving unknown indexed data.
- snmpwalk: retrieving lots of data at once!
- snmptable: displaying a table.
- snmpset: peforming write operations.
- snmpbulkget: communicates with a network entity using SNMP GETBULK request
- snmpbulkwalk: retrieve a sub-tree of management values using SNMP GETBULK requests.
- snmptrap: Sending and receiving traps, and acting upon them.
- Traps/informs with SNMPv3/USM: Sending and receiving SNMPv3/USM TRAPs and INFORMs
- Sending Traps/Informs via AgentX: Sending notifications from the command line through snmpd
- Common command line options:
- Using and loading MIBS
- SNMPv3/USM Options
- Using SNMPv3 over TLS and DTLS
- Customized Output Formats
- Writing mib2c config files
Application Configuration
All of our applications support configuration to allow you to customize how they behave.
Net-SNMP Daemons
Net-SNMP comes with two long-running daemons: a SNMP agent (snmpd) for responding to management requests and a notification receiver (snmptrapd) for receiving SNMP notifications.
Coding Tutorials
Net-SNMP comes with a highly flexible and extensible API. The API allows you to create your own commands, add extensions to the agent to support your own MIBs and perform specialized processing of notifications.
- Client / Manager Coding Tutorials
- Writing a simple application
- Writing a simple asynchronous application
- Agent Coding Tutorials
- The Agent Architecture page might be worth reading before or after the agent coding tutorials, and describes how the Agent Helpers work under the hood.
- Writing a mib module to serve information described by an SNMP MIB, and how to compile it into the net-snmp snmpd agent.
- Writing a Dynamically Loadable Object that can be loaded into the SNMP agent.
- Writing a Subagent that can be run to attach to the snmpd master agent.
- Writing a perl plugin to extend the agent using the NetSNMP::agent module.
- Writing shell scripts to extend the agent
- Using mib2c to help write an agent code template for you
- General mib2c Overview
- Using the mib2c-update script to recode your code
- mib2c.mfd.conf tutorial
- Header files and autoconf
Debugging SNMP Applications and Agents
All our tools and applications have extensive debugging output. These tutorials talk about how the debugging system works and how you can add your own debugging statements to you code:
Источник