/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at * trunk/opends/resource/legal-notices/OpenDS.LICENSE * or https://OpenDS.dev.java.net/OpenDS.LICENSE. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at * trunk/opends/resource/legal-notices/OpenDS.LICENSE. If applicable, * add the following below this CDDL HEADER, with the fields enclosed * by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * * Copyright 2008 Sun Microsystems, Inc. */ // OpenDS imports import org.opends.server.snmp.DIRECTORY_SERVER_MIBOidTable; // OpenDMK imports // import com.sun.management.snmp.SnmpDefinitions; import com.sun.management.snmp.SnmpVarBindList; import com.sun.management.snmp.SnmpEngine; import com.sun.management.snmp.SnmpEngineParameters; import com.sun.management.snmp.SnmpOid; import com.sun.management.snmp.SnmpOidTableSupport; import com.sun.management.snmp.SnmpStatusException; import com.sun.management.snmp.manager.SnmpRequest; import com.sun.management.snmp.manager.SnmpSession; import com.sun.management.snmp.manager.SnmpPeer; import com.sun.management.snmp.manager.SnmpParameters; import com.sun.management.snmp.manager.usm.SnmpUsmPeer; import com.sun.management.snmp.manager.usm.SnmpUsmParameters; /** * This class perform a SNMP get operation. */ public class SNMPGet { /** * Gets the calling arguments. * * @param args SNMP version + SNMP agent host + SNMP agent port + community * @return 0 if the init succeeded or 1 if the init failed */ public int init(String[] args) { int rc = 0; System.out.println("\n"); if (args.length < 5) { // Missing arguments System.out.println( "usage: " + " -v <SNMP version>" + " -h <remoteHost>" + " -p <port>" + " -o <oids>" + " -c <community/context>" + " -u <user>" + " -l <securityLevel>" + " -f <securityFile>" + " -s <connectionStatus>" + " -n <checkOIDs>" + " -w <snmpwalk>"); rc = 1; } else { for (int i = 0; i < args.length; i++) { String opt = args[i]; String val = args[i + 1]; switch (opt.charAt(1)) { case 'v': version = new Integer(val).intValue(); break; case 'h': remoteHost = val; break; case 'p': port = new Integer(val).intValue(); break; case 'o': oids = val; break; case 'c': community = val; break; case 'u': user = val; break; case 'l': if (val.compareTo("noauthnopriv") == 0) { securityLevel = SnmpDefinitions.noAuthNoPriv; } else if (val.compareTo("authnopriv") == 0) { securityLevel = SnmpDefinitions.authNoPriv; } else if (val.compareTo("authpriv") == 0) { securityLevel = SnmpDefinitions.authPriv; } else { System.out.println( "Unknown security level " + opt.charAt(1) + "."); rc = 1; } break; case 'f': securityFile = val; break; case 's': connectStatus = val; break; case 'n': validOIDs = new Boolean(val).booleanValue(); break; case 'w': walk = new Boolean(val).booleanValue(); break; default: System.out.println("Unknown option -" + opt.charAt(1) + "."); rc = 1; } if (rc == 1) { break; } i = i + 1; } } if (rc == 0) { System.out.println("init() of SNMPGet succeeded"); } else { System.out.println("init() of SNMPGet failed"); } return rc; } /** * Open SNMP connection with SNMP agent. * * @return 0 if the connect succeeded or 1 if the connect failed */ public int connect() { int rc = 0; try { // The OidTable generated by mibgen when compiling DIRECTORY_SERVER_MIB // final SnmpOidTableSupport oidTable = new DIRECTORY_SERVER_MIBOidTable(); // Specify the OidTable containing all the DIRECTORY_SERVER_MIB knowledge // SnmpOid.setSnmpOidTable(oidTable); switch (version) { case 1: case 2: // Create the session // session = new SnmpSession("Get V" + version + " session"); // Disable PduFixedOnError option // session.snmpOptions.setPduFixedOnError(false); // Create an SnmpPeer object for representing the entity // to communicate with. // final SnmpPeer agent = new SnmpPeer(remoteHost, port); // Specify the read and write community to be used // final SnmpParameters params = new SnmpParameters( community, community); // Specify the protocol version // switch (version) { case 1: params.setProtocolVersion(SnmpDefinitions.snmpVersionOne); break; case 2: params.setProtocolVersion(SnmpDefinitions.snmpVersionTwo); break; } // Associate the parameters with the agent // agent.setTimeout(timeOut); agent.setMaxTries(maxRetries); agent.setParams(params); // Set the default peer (agent) to a SnmpSession // session.setDefaultPeer(agent); break; case 3: // Custom engine parameters final SnmpEngineParameters engineParameters = new SnmpEngineParameters(); // Activate encryption engineParameters.activateEncryption(); // Set the security file engineParameters.setSecurityFile(securityFile); // Create the session // session = new SnmpSession( engineParameters, null, "Get V3 session", null); // SNMP V3 introduces the notion of SnmpEngine. An engine is // associated to the session. Other objects might need // the engine. You can access it using getEngine method. // final SnmpEngine engine = session.getEngine(); // Create an SnmpUsmPeer object for representing the entity // to communicate with // final SnmpUsmPeer agentV3 = new SnmpUsmPeer(engine, remoteHost, port); // Create USM parameters for the principal defaultuser (user used when // requests are sent: the defaultUser is a template and for this // reason we cannot find it under the user mib (not created as a user) // final SnmpUsmParameters paramsV3 = new SnmpUsmParameters( engine, user); // Set the security level authentication but without privacy // paramsV3.setSecurityLevel(securityLevel); // Set the context name // if (community.compareTo("null") != 0) { paramsV3.setContextName(community.getBytes()); } // Set the contextEngineId discovered by the peer upon // its creation // paramsV3.setContextEngineId(agentV3.getEngineId().getBytes()); // Associate the parameters with the agent // agentV3.setTimeout(timeOut); agentV3.setMaxTries(maxRetries); agentV3.setParams(paramsV3); if (securityLevel != SnmpDefinitions.noAuthNoPriv) { // Discover timeliness of creation and boot // try { agentV3.processUsmTimelinessDiscovery(); } catch (SnmpStatusException e) { if (connectStatus.compareTo("SnmpStatusException") == 0) { System.out.println( "connect() of SNMPGet catched as expected a " + "SNMP status exception: " + e.getMessage() + "\""); } else { System.out.println( "connect() of SNMPGet should not catch a " + "SNMP status exception: " + e.getMessage() + "\""); rc = 1; } } catch (Exception e) { System.out.println( "connect() of SNMPGet catched an unexpected exception: " + e.getMessage() + "\""); rc = 1; } } if (rc == 0) { // Set the default peer (agent) to a SnmpSession // session.setDefaultPeer(agentV3); } break; default: System.out.println( "connect() of SNMPGet: Unknown SNMP version: " + version + " ."); rc = 1; } } catch (Exception e) { System.out.println( "connect() of SNMPGet catched an unexpected exception: " + e.getMessage() + "\""); rc = 1; } if (rc == 0) { System.out.println("connect() of SNMPGet succeeded"); } else { System.out.println("connect() of SNMPGet failed"); } return rc; } /** * Perform an SNMP get request on SNMP agent. * * @return 0 if the getRequest succeeded or 1 if the getRequest failed */ public int getRequest() { int rc = 0; String previousOID = ""; try { // Build the list of variables you want to query // final SnmpVarBindList list = new SnmpVarBindList("Get varbind list"); // Read specific OIDs // if (walk) { // Walk request // list.addVarBind("0.0"); previousOID = "0.0"; } else { // Get request // list.addVarBind(oids); } // Make the SNMP get request // System.out.println( "getRequest() of SNMPGet: Start SNMP V" + version + " GET request for SNMP agent on \"" + remoteHost + "\" at port \"" + port + "\"."); while (previousOID.compareTo("end") != 0) { SnmpRequest request = null; if (walk) { // Walk request // request = session.snmpGetNextRequest(null, list); } else { // Get request // request = session.snmpGetRequest(null, list); } // Check for a timeout of the request // boolean completed = request.waitForCompletion((maxRetries + 1) * timeOut); if (completed == false) { if (connectStatus.compareTo("reqTimeout") != 0) { System.out.println( "getRequest() of SNMPGet: Request timed out, " + "check reachability of agent."); // Print request // System.out.println( "getRequest() of SNMPGet: Request= " + request.toString() + "."); rc = 1; } else { System.out.println( "getRequest() of SNMPGet: Request timed out as expected."); } } if (rc == 0 && completed) { System.out.println( "getRequest() of SNMPGet: Finish SNMP V" + version + " GET request."); // Now we have a response. Check if the response contains an error // String errorStatus = SnmpRequest.snmpErrorToString( request.getErrorStatus()); if (errorStatus.compareTo("noError") != 0) { System.out.println( "getRequest() of SNMPGet: Error status= " + errorStatus + "."); System.out.println( "getRequest() of SNMPGet: Error index= " + request.getErrorIndex() + "."); if (errorStatus.compareTo(connectStatus) == 0) { System.out.println( "getRequest() of SNMPGet: Get request failed as " + "expected with " + connectStatus + " status."); } else { if (walk && errorStatus.compareTo("noSuchName") == 0) { System.out.println( "getRequest() of SNMPGet: Get request failed as " + "expected with " + connectStatus + " status."); } else { System.out.println( "getRequest() of SNMPGet: Get request should " + "fail with " + connectStatus + " status."); rc = 1; } } previousOID = "end"; } else { // Now we shall display the content of the result // SnmpVarBindList resp = request.getResponseVarBindList(); System.out.println("getRequest() of SNMPGet: Result="); String tmpOID = ""; String realOID = ""; for (int i = 0; i < resp.getVarBindCount(); i++) { tmpOID = resp.getVarBindAt(i).getOid().toString(); int endIndex = tmpOID.lastIndexOf("."); String indexOID = tmpOID.substring(endIndex, tmpOID.length()); realOID = tmpOID.substring(0, endIndex); if (realOID.startsWith("1.3.6.1.2.1.66.2")) { endIndex = realOID.lastIndexOf("."); realOID = realOID.substring(0, endIndex); } String name = resp.getVarBindAt(i).resolveVarName(realOID).getName(); String value = resp.getVarBindAt(i).getStringValue(); System.out.println(name + indexOID + "=" + value); if (walk) { list.removeVarBind(previousOID); list.addVarBind(tmpOID); previousOID = tmpOID; } else { previousOID = "end"; } } if (connectStatus.compareTo("noError") != 0) { // Request should failed // System.out.println( "getRequest() of SNMPGet: Get request should " + "fail with " + connectStatus + " status."); rc = 1; } else { if (validOIDs) { // Check that we obtain correct values for the OIDs // if (resp.checkForValidValues()) { System.out.println( "getRequest() of SNMPGet: Returned values for" + " OIDs are correct."); } else { System.out.println( "getRequest() of SNMPGet: Returned values for" + " OIDs are not correct."); rc = 1; } } else { // Check that we obtain incorrect values for the OIDs // if (resp.checkForValidValues()) { System.out.println( "getRequest() of SNMPGet: Returned values for" + " OIDs should not be correct."); rc = 1; } else { System.out.println( "getRequest() of SNMPGet: Returned values for" + " OIDs are not correct as expected."); } } } } } } } catch (Exception e) { System.out.println( "connect() of SNMPGet catched an unexpected exception: " + e.getMessage() + "\""); rc = 1; } if (rc == 0) { System.out.println("getRequest() of SNMPGet succeeded"); } else { System.out.println("getRequest() of SNMPGet failed"); } return rc; } /** * Close SNMP connection with SNMP agent. */ public void disconnect() { // Stop and destroy the SnmpSession if still there try { session.destroySession(); session = null; } catch (Exception e) { // possible session already ended } System.out.println("disconnect() of SNMPGet succeeded"); } /** * Main. * * @param args arguments */ public static void main(String[] args) { SNMPGet client = new SNMPGet(); int rc = 0; // Retrieve parameters rc = client.init(args); // If init() succeeded then open connection if (rc == 0) { rc = client.connect(); } // If connect() succeeded then perform get request if (rc == 0 && connectStatus.compareTo("SnmpStatusException") != 0) { rc = client.getRequest(); } // Close connection client.disconnect(); System.exit(rc); } // Arguments int version = 0; String remoteHost = null; int port = 0; String oids = null; String community = null; String user = null; int securityLevel = SnmpDefinitions.authNoPriv; String securityFile = null; static String connectStatus = null; boolean validOIDs = true; boolean walk = false; // SnmpSession SnmpSession session = null; int timeOut = 30000; // default value int maxRetries = 1; }