Getting started with SNMP4J
The Simple Network Management Protocol (SNMP) is heavily used to manage devices on a network. SNMP4J is an open source SNMP implementation that allows Java programs to create, send and receive SNMP messages. In this post, I will show a simple example to read the raw idle cpu time from a server.
In order to use SNMP4J API, you need to have the following jars in the project classpath:
- snmp-1.3.jar
- SNMP4J.jar
- log4j.jar
The first step is to create a new communication object to connect to the remote host.
InetAddress hostAddress = InetAddress.getByName("remote_host_name"); SNMPv1CommunicationInterface communication = new SNMPv1CommunicationInterface(0, hostAddress, "community_name", 151);
The next step is to query the Management Information Base for the raw idle cpu time.
SNMPVarBindList list = comm.getMIBEntry("1.3.6.1.4.1.2021.11.53.0"); Here 1.3.6.1.4.1.2021.11.53.0 is the OID for the raw idle CPU time.
The final step is to retrieve the value from the returned value. Since we know that the returned list should have only one value, we look up the first item.
SNMPSequence sequence = (SNMPSequence) list.getSNMPObjectAt(0); String idleCPUTime = ((SNMPInteger)sequence.getSNMPObjectAt(1)).toString();
Putting it all together:
import java.net.InetAddress; import snmp.SNMPInteger; import snmp.SNMPSequence; import snmp.SNMPVarBindList; import snmp.SNMPv1CommunicationInterface; public class SnmpLookup { public String getIdleCpuTime(String name, int port,String community) { String idleCPUTime = null; try { InetAddress hostAddress = InetAddress.getByName(name); SNMPv1CommunicationInterface comm = new SNMPv1CommunicationInterface(0, hostAddress, community, port); SNMPVarBindList list = comm.getMIBEntry("1.3.6.1.4.1.2021.11.53.0"); SNMPSequence sequence = (SNMPSequence) list.getSNMPObjectAt(0); idleCPUTime = ((SNMPInteger)sequence.getSNMPObjectAt(1)).toString(); } catch(Exception e) { // Purposefully swalloning the exception } return idleCPUTime; } }
Categories: Getting Started, SNMP4J
Hi,
Thank you for publishing the code.
Where can I find the snmp-1.3.jar ?
Dulop
You should be able to get it from here http://www.snmp4j.org/html/download.html
http://vthr.videolan.org/maven2/snmp/snmp/1.3/
How do I use SNMP4J for MIB parsing?
Please, Post snmp-1.3.jar again. because this link (http://vthr.videolan.org/maven2/snmp/snmp/1.3/) can not download.
Hi there,
Can any one please tell me how to use snmp4j for loading MIB file in agent?