`
gzcj
  • 浏览: 287047 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Implementing an SNMP Proxy

阅读更多
最近因为项目需要,学习jdmk,发现sun提供的例子基本全是english,所以就翻译一篇(顺便提高一下自己)
It is easier to manage a large number of SNMP agents when they have a hierarchical structure of master agents and sub-agents. Master agents concentrate and relay the information in their sub-agents and can provide their own specific information as well. Managers only communicate with the master agents and access the sub-agents transparently, as if the information actually resided in the master agent.

如果采用主agent和子agent的层级结构,就很容易管理大量的snmp agent,主agent集中并传递子agent需要的信息,管理站仅仅跟主agent通讯,由主agent再跟具体的子agent交互,就好像信息是存在于主agent中一样。
In order to do this, agents must contain an SNMP proxy for each sub-agent that they manage. The proxy is a Java class that looks like a MIB MBean to the agent, but which actually accesses the sub-agent to provide the information that is requested of it. In order to access sub-agents, the proxy object relies on the SNMP manager API.

为了达到这一点,agents必须包含(对每一个子agent)snmp代理。代理对于agent来说就像mib bean一样,也是一个java类,但实际上是可提供请求,并访问子agent,为了访问子agent,代理需要使用snmp管理站所使用的api(其实代理注册在主agent中,其能够访问子agent,对于子agent,代理就相当于manager)
分享到:
评论
4 楼 gzcj 2008-07-22  
实现snmp代理(五)
对上一节的代码稍微解释一下:
首先,由客户端发请求给主agent,然后主agent根据请求的方法,传给get或是getnext,再调用相应的方法:
代码如下:
private void getNext(SnmpMibRequest inRequest, int version,
                         SnmpSession session)
        throws SnmpStatusException {
       
        // Construction of the SnmpVarBindList.
        //
        final SnmpVarBindList varbindlist =
            new SnmpVarBindList("SnmpMibAgentImpl varbind list",
                                inRequest.getSubList());

        // Send a GET-NEXT request to the proxied agent and obtain a
        // request handle.
        //
        SnmpRequest request = null;
        try {
            request = session.snmpGetNextRequest(null, varbindlist);
        }
        catch (SnmpStatusException e) {
            throw new SnmpStatusException(SnmpDefinitions.snmpRspGenErr, 0);
        }
        java.lang.System.out.println("\nRequest:\n" + request.toString());

        // Wait for request completion
        //
        boolean completed = request.waitForCompletion(10000);
        if (completed == false) {
            // If the completion failed using SNMP v1, we give up.
            //
            if (version == SnmpDefinitions.snmpVersionOne) {
                java.lang.System.out.println("\nRequest timed out: check " +
                                             "reachability of subagent.");
                return;
            }
            // If the completion failed using SNMP v2, we try the request
            // again using SNMP v1.
            //
            if (version == SnmpDefinitions.snmpVersionTwo) {
                java.lang.System.out.println("\n>> SnmpMibAgentImpl: Try to " +
                                             "submit the getNext request " +
                                             "using SNMP version 1...");
                getNext(inRequest, SnmpDefinitions.snmpVersionOne,
                        sessionV2WithV1);
                return;
            }
        }
3 楼 gzcj 2008-07-22  
实现snmp代理(四)
The SNMP Proxy Implementation
snmp代理的实现

The SNMP proxy is an extension of the abstract SnmpMibAgent which implements all of its abstract methods and can be instantiated. The proxy implements a synchronous SNMP manager that forwards the requests to the sub-agent.
snmp代理是snmpmibagent的扩展,代理实现了一个同步的snmp管理站,并转发请求给子agent。
代码如下:
package proxy;
/*
* @(#)file      SnmpMibAgentImpl.java
* @(#)author    Sun Microsystems, Inc.
* @(#)version   1.35
* @(#)lastedit  04/04/14
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

// java import
//
import java.io.Serializable;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.NoSuchElementException;
import java.net.UnknownHostException;

// RI import
//
import javax.management.ObjectName;
import javax.management.MBeanServer;
import com.sun.management.snmp.SnmpDefinitions;
import com.sun.management.snmp.SnmpOid;
import com.sun.management.snmp.SnmpStatusException;
import com.sun.management.snmp.SnmpVarBind;
import com.sun.management.snmp.SnmpVarBindList;
import com.sun.management.snmp.manager.SnmpPeer;
import com.sun.management.snmp.manager.SnmpParameters;
import com.sun.management.snmp.manager.SnmpRequest;
import com.sun.management.snmp.manager.SnmpSession;

// jdmk import
//
import com.sun.management.snmp.agent.SnmpMibAgent;
import com.sun.management.snmp.agent.SnmpMibRequest;


/**
* The SnmpMibAgentImpl class provides an example of implementation of
* an SNMP proxy.
* It enables an agent to serve remote MIBs
* (that is MIBs running outside the VM where the agent is running).
* In fact, it behaves like a manager on the agent side.
*
* You initialize the SnmpMibAgentImpl invoking the initializeProxy method
* with the following parameters:
*      - host: hostname of the remote SNMP subagent you want to query.
*      - port: port number to use.
*      - strOid: root object identifier of the MIB to query (optional).
*      - name: MIB name (optional).
*/

public class SnmpMibAgentImpl extends SnmpMibAgent implements Serializable {
 
    // INITIALIZATION
    //===============
    /**
     * Initialization of the SnmpMibAgentImpl with no registration in Java DMK.
     * @exception IllegalAccessException The SnmpMibAgentImpl can not be
     *            initialized.
     */
    public void init() throws IllegalAccessException {
    }
 
    /**
     * Initialization of the SnmpMibAgentImpl with registration in Java DMK.
     * @param server The reference to the MBean server.
     * @param name The object name of this SnmpMibAgentImpl.
     */
    public ObjectName preRegister(MBeanServer server, ObjectName name)
        throws Exception {
         
        // Initialize MBeanServer information.
        //
        this.server = server;
        return name;
    }
 
    /**
     * Initialization of the proxy stuff.
     * @param h The hostname of the remote SNMP subagent.
     * @param p The port number to use.
     * @param strOid The root object identifier of the MIB.
     * @param name The name of the MIB.
     * @exception UnknownHostException The hostname can not be resolved.
     * @exception SnmpStatusException An error occurred while accessing
     *            a MIB node.
     */
    public void initializeProxy(String h, int p, String strOid, String name)
        throws UnknownHostException, SnmpStatusException {
       
        host = h;
        port = p;
        oid = strOid;
        mibName = name;
       
        // Initialization for SNMP v1 protocol.
        //
        SnmpParameters paramsV1 = new SnmpParameters("public", "private");
        paramsV1.setProtocolVersion(SnmpDefinitions.snmpVersionOne);
        SnmpPeer peerV1 = new SnmpPeer(host, port);
        peerV1.setParams(paramsV1);
        sessionV1 = new SnmpSession("SnmpMibAgentImpl session V1");
        sessionV1.setDefaultPeer(peerV1);
        // Using SNMP v1 protocol, the error is not fixed but is forwarded
        // to the manager.
        //
        sessionV1.snmpOptions.setPduFixedOnError(false);

        // Initialization for SNMP v2 protocol.
        //
        SnmpParameters paramsV2 = new SnmpParameters("public", "private");
        paramsV2.setProtocolVersion(SnmpDefinitions.snmpVersionTwo);
        SnmpPeer peerV2 = new SnmpPeer(host, port);
        peerV2.setParams(paramsV2);
        // If we meet a problem, we don't retry the request using SNMP v2
        // but we try the request using SNMP v1.
        //
        peerV2.setMaxTries(0);
        sessionV2 = new SnmpSession("SnmpMibAgentImpl session V2");
        sessionV2.setDefaultPeer(peerV2);
        // Using SNMP v2 protocol, the error is fixed.
        //
        sessionV2.snmpOptions.setPduFixedOnError(true);

        // Initialization for SNMP v2 protocol simulated using SNMP v1
        // protocol.
        //
        sessionV2WithV1 =
            new SnmpSession("SnmpMibAgentImpl session V2 with V1");
        sessionV2WithV1.setDefaultPeer(peerV1);
        // Simulating SNMP v2 with SNMP v1 protocol, the error is fixed.
        //
        sessionV2WithV1.snmpOptions.setPduFixedOnError(true);
    }
 
    /**
     * Initialization of the proxy stuff.
     * @param h The hostname of the remote SNMP subagent.
     * @param p The port number to use.
     * @param strOid The root object identifier of the MIB.
     * @exception UnknownHostException The hostname can not be resolved.
     * @exception SnmpStatusException An error occurred while accessing
     *            a MIB node.
     */
    public void initializeProxy(String h, int p, String strOid)
        throws UnknownHostException, SnmpStatusException {
        initializeProxy(h, p, strOid, "SnmpMibAgentImpl");
    }
 
    /**
     * Initialization of the proxy stuff.
     * @param h The hostname of the remote SNMP subagent.
     * @param p The port number to use.
     * @exception UnknownHostException The hostname can not be resolved.
     * @exception SnmpStatusException An error occurred while accessing
     *            a MIB node.
     */
    public void initializeProxy(String h, int p)
        throws UnknownHostException, SnmpStatusException {
        initializeProxy(h, p, null, "SnmpMibAgentImpl");
    }
 

    // SNMP PROXY STUFF
    //=================
    /**
     * Implement the get method from the abstract SnmpMibAgent class.
     * If the protocol version is V2 and if the operation fails using
     * version 2 of SNMP, we try it again using version 1.
     *
     * @param inRequest The SnmpMibRequest object holding the list of variable
     *                  to be retrieved. This list is composed of
     *                  <CODE>SnmpVarBind</CODE> objects.
     *
     * @return The varbinds in the SnmpMibRequest object are updated with
     *         the proxied agent returned values.
     * @exception SnmpStatusException  An error occurred during the operation.
     */
    public void get(SnmpMibRequest inRequest) throws SnmpStatusException {
                                         
        java.lang.System.out.println("\n>> ================================" +
                                     "=====================================");
        java.lang.System.out.println(">> SnmpMibAgentImpl: Sending get " +
                                     "request to SNMP subagent on " +
                                     host + " using port " + port);

        // Get the protocol version
        //
        final int version = inRequest.getVersion();

        // Request using SNMP v1 protocol.
        //
        if (version == SnmpDefinitions.snmpVersionOne) {
            get(inRequest, version, sessionV1);
        }
        // Request using SNMP v2 protocol.
        //
        if (version == SnmpDefinitions.snmpVersionTwo) {
            get(inRequest, version, sessionV2);
        }
    }

    /**
     * Implement the set method from the abstract SnmpMibAgent class.
     * If the protocol version is V2 and if the operation fails using
     * version 2 of SNMP, we try it again using version 1.
     *
     * @param inRequest The SnmpMibRequest object holding the list of
     *            variables to be retrieved. This list is composed of
     *            <CODE>SnmpVarBind</CODE> objects.
     *
     * @return The varbinds in the SnmpMibRequest object are updated with
     *         the proxied agent returned values.
     *
     * @exception SnmpStatusException  An error occurred during the operation.
     */
    public void set(SnmpMibRequest inRequest) throws SnmpStatusException {
       
        java.lang.System.out.println("\n>> ================================" +
                                     "=====================================");
        java.lang.System.out.println(">> SnmpMibAgentImpl: Sending set " +
                                     "request to SNMP subagent on " +
                                     host + " using port " + port);

        // Get the protocol version
        //
        final int version = inRequest.getVersion();

        // Request using SNMP v1 protocol.
        //
        if (version == SnmpDefinitions.snmpVersionOne) {
            set(inRequest, version, sessionV1);
        }
        // Request using SNMP v2 protocol.
        //
        if (version == SnmpDefinitions.snmpVersionTwo) {
            set(inRequest, version, sessionV2);
        }
    }
 
    /**
     * Implement the getNext method from the abstract SnmpMibAgent class.
     * If the protocol version is V2 and if the operation fails using
     * version 2 of SNMP, we try it again using version 1.
     *
     * @param inRequest The SnmpMibRequest object holding the list of
     *            OIDs from which the next variables should be retrieved.
     *            This list is composed of <CODE>SnmpVarBind</CODE> objects.
     *
     * @return The varbinds in the SnmpMibRequest object are updated with
     *         the proxied agent returned values.
     *
     * @exception SnmpStatusException  An error occurred during the operation.
     */
    public void getNext(SnmpMibRequest inRequest) throws SnmpStatusException {
//如果客户端调用使用的是getnext的,则在agent端调用相应的方法getnext
       
        java.lang.System.out.println("\n>> ================================" +
                                     "=====================================");
        java.lang.System.out.println(">> SnmpMibAgentImpl: Sending getNext " +
                                     "request to SNMP subagent on " +
                                     host + " using port " + port);

        // Get the protocol version
        //
        final int version = inRequest.getVersion();

        // Request using SNMP v1 protocol.
        //
        if (version == SnmpDefinitions.snmpVersionOne) {
            getNext(inRequest, version, sessionV1);
        }
        // Request using SNMP v2 protocol.
        //
//不知道为什么从inRequest得到的是version是1,在manager端是设置哪个参数,
//没有弄清楚
        if (version == SnmpDefinitions.snmpVersionTwo) {
            getNext(inRequest, version, sessionV2);
        }
    }
   
    /**
     * Not implemented.
     */
    public void getBulk(SnmpMibRequest inRequest, int nonRepeat, int maxRepeat)
        throws SnmpStatusException {
        return;
    }
 
    /**
     * This method allows to specify both the protocol version and the
     * session to use for the get request.
     *
     * If the request was originally sent using SNMP v1,
     * the session does not fix the error but forwards it to the manager.
     * If the request was sent using SNMP v1 to simulate SNMP v2,
     * the session fixes the error.
     */
    private void get(SnmpMibRequest inRequest, int version,
                     SnmpSession session)
        throws SnmpStatusException {
                                         
        // Construction of the SnmpVarBindList.
        //
        final SnmpVarBindList varbindlist =
            new SnmpVarBindList("SnmpMibAgentImpl varbind list",
                                inRequest.getSubList());

        // Send a GET request to the proxied agent and obtain a request handle.
        //
        SnmpRequest request = null;
        try {
            request = session.snmpGetRequest(null, varbindlist);
        }
        catch (SnmpStatusException e) {
            throw new SnmpStatusException(SnmpDefinitions.snmpRspGenErr, 0);
        }
        java.lang.System.out.println("\nRequest:\n" + request.toString());
           
        // Wait for request completion
        //
        boolean completed = request.waitForCompletion(10000);
        if (completed == false) {
            // If the completion failed using SNMP v1, we give up.
            //
            if (version == SnmpDefinitions.snmpVersionOne) {
                java.lang.System.out.println("\nRequest timed out: check " +
                                             "reachability of subagent.");
                return;
            }
            // If the completion failed using SNMP v2, we try the request
            // again using SNMP v1.
            //
            if (version == SnmpDefinitions.snmpVersionTwo) {
                java.lang.System.out.println("\n>> SnmpMibAgentImpl: Try to " +
                                             "submit the get request using " +
                                             "SNMP version 1...");
                get(inRequest, SnmpDefinitions.snmpVersionOne, sessionV2WithV1);
                return;
            }
        }

        // Check request result
        //
        final int errorStatus = request.getErrorStatus();
        final int errorIndex = request.getErrorIndex() + 1;
        if (errorStatus != SnmpDefinitions.snmpRspNoError) {
            java.lang.System.out.println("\nError status = " +
                                 SnmpRequest.snmpErrorToString(errorStatus));
            java.lang.System.out.println("Error index = " + errorIndex);
            // If there is an error status using SNMP v1, we throw an
            // exception.
            //
            if (version == SnmpDefinitions.snmpVersionOne) {
                throw new SnmpStatusException(errorStatus, errorIndex);
            }
            // If there is an error status using SNMP v2, we try the
            // request again using SNMP v1.
            //
            if (version == SnmpDefinitions.snmpVersionTwo) {
                java.lang.System.out.println("\n>> SnmpMibAgentImpl: Try to " +
                                             "submit the get request using " +
                                             "SNMP version 1...");
                get(inRequest, SnmpDefinitions.snmpVersionOne, sessionV2WithV1);
                return;
            }
        }

        // Display the returned values
        //
        final SnmpVarBindList result = request.getResponseVarBindList();
        java.lang.System.out.println("\nResult: \n" +
                                     result.varBindListToString());

        // Update the inRequest parameter.
        // The varbinds in the result list are expected to be in the same
        // order than in the request, so we can safely loop sequentially
        // over both lists.
        //
        Enumeration l = inRequest.getElements();
        for (Enumeration e = result.elements(); e.hasMoreElements();) {
            SnmpVarBind varres = (SnmpVarBind) e.nextElement();
            SnmpVarBind varbind = (SnmpVarBind) l.nextElement();
            varbind.setSnmpValue(varres.getSnmpValue());
        }
    }

    /**
     * This method allows to specify both the protocol version and the
     * session to use for the set request.
     *
     * If the request was originally sent using SNMP v1,
     * the session does not fix the error but forwards it to the manager.
     * If the request was sent using SNMP v1 to simulate SNMP v2, the
     * session fixes the error.
     */
    private void set(SnmpMibRequest inRequest, int version,
                     SnmpSession session)
        throws SnmpStatusException {
       
        // Construction of the SnmpVarBindList.
        //
        final SnmpVarBindList varbindlist =
            new SnmpVarBindList("SnmpMibAgentImpl varbind list",
                                inRequest.getSubList());

        // Send a SET request to the proxied agent and obtain a request
        // handle.
        //
        SnmpRequest request = null;
        try {
            request = session.snmpSetRequest(null, varbindlist);
        }
        catch (SnmpStatusException e) {
            throw new SnmpStatusException(SnmpDefinitions.snmpRspGenErr, 0);
        }
        java.lang.System.out.println("\nRequest:\n" + request.toString());
        
        // Wait for request completion
        //
        boolean completed = request.waitForCompletion(10000);
        if (completed == false) {
            // If the completion failed using SNMP v1, we give up.
            //
            if (version == SnmpDefinitions.snmpVersionOne) {
                java.lang.System.out.println("\nRequest timed out: check " +
                                             "reachability of subagent.");
                return;
            }
            // If the completion failed using SNMP v2, we try the request
            // again using SNMP v1.
            //
            if (version == SnmpDefinitions.snmpVersionTwo) {
                java.lang.System.out.println("\n>> SnmpMibAgentImpl: Try to " +
                                             "submit the set request using " +
                                             "SNMP version 1...");
                set(inRequest, SnmpDefinitions.snmpVersionOne, sessionV2WithV1);
                return;
            }
        }

        // Check the request result
        //
        int errorStatus = request.getErrorStatus();
        int errorIndex = request.getErrorIndex() + 1;
        if (errorStatus != SnmpDefinitions.snmpRspNoError) {
            java.lang.System.out.println("\nError status = " +
                                 SnmpRequest.snmpErrorToString(errorStatus));
            java.lang.System.out.println("Error index = " + errorIndex);
            // If there is an error status using SNMP v1, we throw an
            // exception.
            //
            if (version == SnmpDefinitions.snmpVersionOne) {
                throw new SnmpStatusException(errorStatus, errorIndex);
            }
            // If there is an error status using SNMP v2, we try the
            // request again using SNMP v1.
            //
            if (version == SnmpDefinitions.snmpVersionTwo) {
                java.lang.System.out.println("\n>> SnmpMibAgentImpl: Try to " +
                                             "submit the set request using " +
                                             "SNMP version 1...");
                set(inRequest, SnmpDefinitions.snmpVersionOne, sessionV2WithV1);
                return;
            }
        }

        // Display the returned values
        //
        final SnmpVarBindList result = request.getResponseVarBindList();
        java.lang.System.out.println("\nResult: \n" +
                                     result.varBindListToString());

        // Update the inRequest parameter.
        // The varbinds in the result list are expected to be in the same
        // order than in the request, so we can safely loop sequentially
        // over both lists.
        //
        final Enumeration l = inRequest.getElements();
        for (Enumeration e = result.elements(); e.hasMoreElements();) {
            SnmpVarBind varres = (SnmpVarBind) e.nextElement();
            SnmpVarBind varbind = (SnmpVarBind) l.nextElement();
            varbind.setSnmpValue(varres.getSnmpValue());
        }
    }

    /**
     * This method allows to specify both the protocol version and the
     * session to use for the getNext request.
     *
     * If the request was originally sent using SNMP v1, the session
     * does not fix the error but forwards it to the manager.
     * If the request was sent using SNMP v1 to simulate SNMP v2, the
     * session fixes the error.
     */
    private void getNext(SnmpMibRequest inRequest, int version,
                         SnmpSession session)
        throws SnmpStatusException {
     
        // Construction of the SnmpVarBindList.
        //
        final SnmpVarBindList varbindlist =
            new SnmpVarBindList("SnmpMibAgentImpl varbind list",
                                inRequest.getSubList());

        // Send a GET-NEXT request to the proxied agent and obtain a
        // request handle.
        //
        SnmpRequest request = null;
        try {
            request = session.snmpGetNextRequest(null, varbindlist);
        }
        catch (SnmpStatusException e) {
            throw new SnmpStatusException(SnmpDefinitions.snmpRspGenErr, 0);
        }
        java.lang.System.out.println("\nRequest:\n" + request.toString());

        // Wait for request completion
        //
        boolean completed = request.waitForCompletion(10000);
        if (completed == false) {
            // If the completion failed using SNMP v1, we give up.
            //
            if (version == SnmpDefinitions.snmpVersionOne) {
                java.lang.System.out.println("\nRequest timed out: check " +
                                             "reachability of subagent.");
                return;
            }
            // If the completion failed using SNMP v2, we try the request
            // again using SNMP v1.
            //
            if (version == SnmpDefinitions.snmpVersionTwo) {
                java.lang.System.out.println("\n>> SnmpMibAgentImpl: Try to " +
                                             "submit the getNext request " +
                                             "using SNMP version 1...");
                getNext(inRequest, SnmpDefinitions.snmpVersionOne,
                        sessionV2WithV1);
                return;
            }
        }

        // Check the request result
        //
        int errorStatus = request.getErrorStatus();
        int errorIndex = request.getErrorIndex() + 1;
        if (errorStatus != SnmpDefinitions.snmpRspNoError) {
            java.lang.System.out.println("\nError status = " +
                                 SnmpRequest.snmpErrorToString(errorStatus));
            java.lang.System.out.println("Error index = " + errorIndex);
            // If there is an error status using SNMP v1, we throw an
            // exception.
            //
            if (version == SnmpDefinitions.snmpVersionOne) {
                throw new SnmpStatusException(errorStatus, errorIndex);
            }
            // If there is an error status using SNMP v2, we try the
            // request again using SNMP v1.
            //
            if (version == SnmpDefinitions.snmpVersionTwo) {
                java.lang.System.out.println("\n>> SnmpMibAgentImpl: Try to " +
                                             "submit the getNext request " +
                                             "using SNMP version 1...");
                getNext(inRequest, SnmpDefinitions.snmpVersionOne,
                        sessionV2WithV1);
                return;
            }
        }

        // Display the returned values
        //
        final SnmpVarBindList result = request.getResponseVarBindList();
        java.lang.System.out.println("\nResult: \n" +
                                     result.varBindListToString());

        // Update the inRequest parameter.
        // The varbinds in the result list are expected to be in the same
        // order than in the request, so we can safely loop sequentially
        // over both lists. Since we parse the result of a GET-NEXT
        // request, we must also copy the value of the returned OIDs
        //
        Enumeration l = inRequest.getElements();
        for (Enumeration e = result.elements(); e.hasMoreElements();) {
            SnmpVarBind varres = (SnmpVarBind) e.nextElement();
            SnmpVarBind varbind = (SnmpVarBind) l.nextElement();
            varbind.setOid(varres.getOid());
            varbind.setSnmpValue(varres.getSnmpValue());
        }
    }
 
    /**
     * Parse the string oid and return the corresponding root object
     * identifier.
     */
    private long[] resolveOidString(String s) {
        SnmpOid oid = new SnmpOid(s);
        return oid.longValue();
    }
 
    // GETTER/SETTER
    //==============
   
    /**
     * Return the root object identifier of the MIB.
     */
    public long[] getRootOid() {
       
        // A string oid has been initialized by the user.
        //
        if (oid != null) {
            rootOid = resolveOidString(oid);
        }
       
        // No initialization of the oid string has been done by the user.
        //
        else {
            try {
                final Vector varBindList = new Vector();
                final SnmpOid varBindOid = new SnmpOid("0.0");
                final SnmpVarBind varBind = new SnmpVarBind(varBindOid, null);
                final int version = SnmpDefinitions.snmpVersionTwo;
                varBindList.addElement(varBind);

                SnmpMibRequest inRequest =
                SnmpMibAgent.newMibRequest(null, varBindList, version, null);
               
                getNext(inRequest);
               
                // As the 3 last ids cannot be part of the root oid
                // (either if the string represent a "simple" variable or
                // a table instance), we remove them from the string oid.
                // Note that this will not always work, but we're trying
                // our best guess. To avoid to enter this code, it is
                // recommended to give the string OID at proxy initialization.
                //
                String strOid = varBind.getOid().toString();
                int index = strOid.lastIndexOf('.');
                for (int i = 1; i <= 3; i++) {
                    strOid = strOid.substring(0, index);
                    index = strOid.lastIndexOf('.');
                }
                rootOid = resolveOidString(strOid);
            }
            catch (Exception e) {
                java.lang.System.out.println("\nProblem when resolving the " +
                                             "string oid...");
            }
        }
       
        return rootOid;
    }
 
    public String getHost() {
        return host;
    }
    public void setHost(String s) {
        host = s;
    }
 
    public int getPort() {
        return port;
    }
    public void setPort(int i) {
        port = i;
    }
 
    public String getOid() {
        return oid;
    }
    public void setOid(String s) {
        oid = s;
    }
 
    // PRIVATE VARIABLES
    //==================
    private String host = null;
    private int port = 0;
    private String oid = null;
 
    private SnmpSession sessionV1 = null;
    private SnmpSession sessionV2 = null;
    private SnmpSession sessionV2WithV1 = null;
 
    private transient long[] rootOid = null;
}

2 楼 gzcj 2008-07-22  
实现snmp代理(三)
举个例子
//master agent
package proxy;
/*@(#)file      Agent.java
* @(#)author    Sun Microsystems, Inc.
* @(#)version   1.32
* @(#)lastedit  04/04/07
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

// JMX imports
//
import javax.management.ObjectName;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;

// JDMK imports
//
import com.sun.jdmk.comm.HtmlAdaptorServer;
import com.sun.management.comm.SnmpAdaptorServer;
import com.sun.management.snmp.agent.SnmpMibAgent;

/**
* The Agent class provides an example on how to use the SNMP proxy.
* This agent is able to serve remote MIBs
* (that is MIBs running outside the VM where the agent is running).
* It acts as the single point of contacts for a set of MIBs or subagents.
*
* A local DEMO_MIB is loaded and initialized.
* An SNMP proxy is initialized and allows to query remote MIBs.
*
* The SNMP protocol adaptor of the agent is started on port 8085.
* The SNMP proxy will query the specified host using the specified
* port number.
*/

public class Agent {

    /**
     * The main method allows you to specify the following optional
     * command-line parameters:
     *  1) host: hostname of the remote SNMP subagent you want to query.
     *  2) port: port number of the remote SNMP subagent you want to query.
     */
    public static void main(String argv[]) {

        MBeanServer server;
        ObjectName htmlObjName;
        ObjectName snmpObjName;
        ObjectName localMibObjName;
        ObjectName remoteMibObjName;
        String host;
        String port;
        int htmlPort = 8082;
        int snmpPort = 8085;

//        if (argv.length != 2) {
//            usage();
//            java.lang.System.exit(1);
//        }

        host = "127.0.0.1";
        port = "8086";

        try {
            server = MBeanServerFactory.createMBeanServer();
            String domain = server.getDefaultDomain();

            // Create and start the HTML adaptor.
            //
            htmlObjName =
new ObjectName(domain +
       ":class=HtmlAdaptorServer,protocol=html,port=" +
       htmlPort);
            java.lang.System.out.println("Adding HTML adaptor to MBean " +
"server with name \n\t" + htmlObjName);
            java.lang.System.out.println("NOTE: HTML adaptor is bound to " +
"TCP port " + htmlPort);
            HtmlAdaptorServer htmlAdaptor = new HtmlAdaptorServer(htmlPort);
            server.registerMBean(htmlAdaptor, htmlObjName);
            htmlAdaptor.start();

            // Create and start the SNMP adaptor.
            //
            snmpObjName =
new ObjectName(domain +
       ":class=SnmpAdaptorServer,protocol=snmp,port=" +
       snmpPort);
            java.lang.System.out.println("Adding SNMP adaptor to MBean " +
"server with name \n\t" + snmpObjName);
            java.lang.System.out.println("NOTE: SNMP Adaptor is bound to " +
"UDP port " + snmpPort);
            SnmpAdaptorServer snmpAdaptor = new SnmpAdaptorServer(snmpPort);
            server.registerMBean(snmpAdaptor, snmpObjName);
            snmpAdaptor.start();

            // Create and initialize the local MIB Demo.
            //此处不注册本地mbean
//            localMibObjName = new ObjectName("snmp:class=DEMO_MIB");
//            java.lang.System.out.println("Adding DEMO_MIB to MBean server " +
// "with name \n\t" + localMibObjName);
//            DEMO_MIB localMib = new DEMO_MIB_IMPL();
//            server.registerMBean(localMib, localMibObjName);
//            java.lang.System.out.println("\nInitializing the MIB " +
// localMibObjName);

            // Bind the SNMP adaptor to the MIB in order to make the MIB
    // accessible through the SNMP protocol.
            //
//            localMib.setSnmpAdaptor(snmpAdaptor);

            // Create and initialize the SNMP proxy.
            //
            remoteMibObjName = new ObjectName("snmp:class=proxy");
            java.lang.System.out.println("Adding proxy to MBean server " +
"with name \n\t" + remoteMibObjName);
            SnmpMibAgentImpl remoteMib = new SnmpMibAgentImpl();
//注册代理,将会调用SnmpMibAgentImpl的preRegister
            server.registerMBean(remoteMib, remoteMibObjName);
//初始代理
            remoteMib.initializeProxy(host, Integer.parseInt(port),
      "1.3.6.1.2.1");
            java.lang.System.out.println("\nInitializing the SNMP proxy " +
remoteMibObjName +  " to query host " +
host + " using port " + port);

            // Bind the SNMP adaptor to the MIB in order to make the MIB
    // accessible through the SNMP protocol.
            //
            remoteMib.setSnmpAdaptor(snmpAdaptor);
        } catch (Exception e) {
            java.lang.System.err.println("\nException occurred: " + e );
            e.printStackTrace();
            java.lang.System.exit(1);
        }
    }
   }
1 楼 gzcj 2008-07-22  
实现snmp代理(二)
The main MBean extends the SnmpMib class whose implementation of the abstract SnmpMibAgent class processes all requests on a MIB.
(如果使用过mibgen工具的人,都知道能够由mib文件生成一个主mbean,例如:RFC1213_MIB.java)这个主mbean继承了snmpmib类,而snmpmib则是对抽象类snmpmibagent的实现,SnmpMib 可处理所有关于mib的请求。

For example, if an agent receives a get request for some variable, it will call the get method that the main MBean inherits from SnmpMibAgent. The implementation of this method relies on the MIB structure to find the MBean containing the corresponding attribute and then call its getter to read the value of the variable.
举个例子,如果一个agent收到一个关于某些变量的请求,它将调用继承于snmpmibagent的主mbean的get方法,这个方法依靠mib的文件结构,能够找到mbean所包含的对应的属性,并且能够读取这个变量的值。

A proxy is another implementation of the SnmpMibAgent class which, instead of resolving variables in local MBeans, reformulates an SNMP request, sends it to a designated sub-agent and forwards the answer that it receives. Since only the main MBean of a MIB is bound to the SNMP adaptor, we bind the proxy instead, and the master agent transparently exposes the MIB which actually resides in the sub-agent.
一个代理是snmpmibagent的另一种实现,他并不在本地mbeans里解析变量,而是再形成一个snmp请求,把该请求送到指定的子代理,并转发从子代理得到的结果。在普通的agent中仅只有主mbean被绑定到snmp适配器上,对于含有代理的agent,我们需要把代理也绑定到相应的适配器上。主agent处理的mib其实是在子agent上执行的,但对于管理站来说就好像在主agent上执行的处理一样。


相关推荐

Global site tag (gtag.js) - Google Analytics