Package

Source Code of SNMPSet

/*
* 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/nasutekds/resource/legal-notices/NasuTekDS.LICENSE
* or https://NasuTekDS.dev.java.net/NasuTekDS.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/nasutekds/resource/legal-notices/NasuTekDS.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.
*/

// NasuTekDS imports
import org.nasutekds.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.SnmpString;
import com.sun.management.snmp.SnmpVarBind;
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 set operation.
*/
public class SNMPSet {

  /**
   * Gets the calling arguments.
   *
   * @param args SNMP agent version + SNMP agent host + SNMP agent port
   * @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>" +
              " -u <user>" +
              " -l <securityLevel>" +
              " -f <securityFile>" +
              " -s <connectionStatus>" +
              " -n <checkOIDs>");
      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;
          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 SNMPSet succeeded");
    } else {
      System.out.println("init() of SNMPSet 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("Set V" + version + " session");

          // 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;
            default:
              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,
                  "Set 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);

          // Discover timeliness of creation and boot
          //
         try {
            agentV3.processUsmTimelinessDiscovery();
         } catch (SnmpStatusException e) {
           if (connectStatus.compareTo("SnmpStatusException") == 0) {
             System.out.println(
                     "connect() of SNMPSet catched as expected a " +
                     "SNMP status exception: " + e.getMessage() + "\"");
           } else {
             System.out.println(
                     "connect() of SNMPSet should not catch a " +
                     "SNMP status exception: " + e.getMessage() + "\"");

             rc = 1;
           }
          } catch (Exception e) {
            System.out.println(
                    "connect() of SNMPSet 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 SNMPSet: Unknown SNMP version: "
                  + version + " .");

          rc = 1;
      }
    } catch (Exception e) {
      System.out.println(
              "connect() of SNMPSet catched an unexpected exception: " +
              e.getMessage() + "\"");

      rc = 1;
    }

    if (rc == 0) {
      System.out.println("connect() of SNMPSet succeeded");
    } else {
      System.out.println("connect() of SNMPSet succeeded");
    }

    return rc;
  }

  /**
   * Perform an SNMP set request on SNMP agent.
   *
   * @return 0 if the setRequest succeeded or 1 if the setRequest failed
   */
  public int setRequest() {
    int rc = 0;

    try {
      // Build the list of variables you want to query
      //
      final SnmpVarBindList list = new SnmpVarBindList("Get varbind list");

      // Write one specific OID
      //
      SnmpVarBind oid = new SnmpVarBind(oids);
      oid.setSnmpValue(new SnmpString("myValue"));
      list.addVarBind(oid);

      // Make the SNMP set request
      //
      System.out.println(
              "setRequest() of SNMPSet: Start SNMP V" + version +
              " GET request for SNMP agent on \"" + remoteHost +
              "\" at port \"" + port + "\".");

      // Set request
      //
      SnmpRequest request = session.snmpSetRequest(null, list);

      // Check for a timeout of the request
      //
      boolean completed = request.waitForCompletion((maxRetries + 1) * timeOut);
      if (completed == false) {
        System.out.println(
                "setRequest() of SNMPSet: Request timed out, " +
                "check reachability of agent.");

        // Print request
        //
        System.out.println(
                "setRequest() of SNMPSet: Request= " +
                request.toString() + ".");

        rc = 1;
      }

      if (rc == 0) {
        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 {
            System.out.println(
                    "getRequest() of SNMPGet: Get request should " +
                    "fail with " + connectStatus + " status.");

            rc = 1;
          }
        } else {
          // Now we shall display the content of the result
          //
          SnmpVarBindList resp = request.getResponseVarBindList();

          System.out.println("getRequest() of SNMPGet: Result=");

          for (int i = 0; i < resp.getVarBindCount(); i++) {
            System.out.println(resp.getVarBindAt(i));
          }

          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(
              "setRequest() of SNMPSet catched an unexpected exception: " +
              e.getMessage() + "\"");

      rc = 1;
    }

    if (rc == 0) {
      System.out.println("setRequest() of SNMPSet succeeded");
    } else {
      System.out.println("setRequest() of SNMPSet 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 SNMPSet succeeded");
  }

  /**
   * Main.
   *
   * @param args arguments
   */
  public static void main(String[] args) {

    SNMPSet client = new SNMPSet();

    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 set request
    if (rc == 0 && connectStatus.compareTo("SnmpStatusException") != 0) {
      rc = client.setRequest();
    }

    // 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;

  // SnmpSession
  SnmpSession session = null;

  int timeOut = 30000// default value
  int maxRetries = 1;
}
TOP

Related Classes of SNMPSet

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.