如何使用SNMP4J创建SNMP代理模拟器

时间:2020-10-27 21:25:31

标签: java network-programming snmp agent snmp4j

因此,我尝试使用Java库SNMP4j在本地计算机上运行代理模拟。我一直在使用此示例程序来尝试使一切正常运行。

https://www.jitendrazaa.com/blog/java/snmp/creating-snmp-agent-server-in-java-using-snmp4j/

设置环境时遇到了一些麻烦,因此我参考了这篇帖子RunTimeException in SNMP4J agent来寻求帮助。导入他的项目后,我遇到了与他同样的约束问题。

要解决此问题,我刚刚将模拟代理的IP地址从0.0.0.1/161更改为127.0.0.1/16000。现在,我收到此运行时错误:

Exception in thread "main" java.lang.NullPointerException
at org.snmp4j.agent.mo.DefaultMOTableModel.addRow(DefaultMOTableModel.java:44)
at org.snmp4j.agent.mo.DefaultMOMutableTableModel.addRow(DefaultMOMutableTableModel.java:285)
at org.snmp4j.agent.mo.DefaultMOTable.addRow(DefaultMOTable.java:191)
at org.bihe.SNMPAgent.addCommunities(SNMPAgent.java:87)
at org.snmp4j.agent.BaseAgent.init(BaseAgent.java:175)
at org.bihe.SNMPAgent.start(SNMPAgent.java:166)
at org.bihe.TestSNMPAgent.init(TestSNMPAgent.java:44)
at org.bihe.TestSNMPAgent.main(TestSNMPAgent.java:19)

我将范围缩小到baseAgent类尝试使用SNMPAgent类中重载的addCommunities函数时。在此函数中,由于SNMP4j库提供的DefaultMOTable类中的这段代码,MOTableRow行变量被分配为null。

不是获取SNMP_Error_Success代码“ 0”,而是获取rowEvent.getVetoStatus()为“ 18”。这样就得到了NULL的返回值

public R createRow(OID index, Variable[] initialValues) {
if (model instanceof MOMutableTableModel) {
  Variable[] values = initialValues;
  if (values.length < getColumnCount()) {
    values = getDefaultValues();
    System.arraycopy(initialValues, 0, values, 0, initialValues.length);
  }
  R row =
      ((MOMutableTableModel<R>)model).createRow(index, values);
  MOTableRowEvent rowEvent =
      new MOTableRowEvent(this, this, row, MOTableRowEvent.CREATE, true);
  fireRowChanged(rowEvent);
  //this is where things go wrong
  System.out.println(rowEvent.getVetoStatus());
  if (rowEvent.getVetoStatus() == SnmpConstants.SNMP_ERROR_SUCCESS) {
    return row;
  }
}
return null;
}

我在SNMPConstants.class文件中查找了此错误代码,发现错误状态为18表示“ SNMP_ERROR_INCONSISTENT_NAME = 18”。我很难弄清楚这到底是什么意思,是什么导致此错误以及如何修复它。我正在使用与上述项目“ snmp4j-2.2.3.jar”和“ snmp4j-agent-2.0.10a.jar”完全相同的罐子。

如果有帮助,这是我正在使用的代码:

  package org.bihe;

  import java.io.IOException;

  import org.snmp4j.agent.CommandProcessor;
  import org.snmp4j.mp.MPv3;
  import org.snmp4j.smi.OID;
  import org.snmp4j.smi.OctetString;
  import org.snmp4j.mp.SnmpConstants;

public class TestSNMPAgent {

static final OID sysDescr = new OID(".1.3.6.1.2.1.1.1.0");

public static void main(String[] args) throws IOException {

    //not really sure what the use of this ipaddress is as it't not used anywhere in the code.
    TestSNMPAgent client = new TestSNMPAgent("udp:127.0.0.1/161");
    System.out.println("Hello this is a client");
    client.init();
}

SNMPAgent agent = null;
/**
 * This is the client which we have created earlier
 */
SNMPManager client = null;

String address = null;

/**
 * Constructor
 *
 * @param add
 */
public TestSNMPAgent(String add) {
    address = add;
}

private void init() throws IOException {
    System.out.println("Hello before Agent");
    OctetString testoct = new OctetString("public2public");
    
    //ipaddress changed from 0.0.0.1/161 to 127.0.0.1/16000
    agent = new SNMPAgent("127.0.0.1/16000");
    agent.start();
    //code execution doesn't make it past the agent.start() statement.
    System.out.println("Hello after agent");

    // Since BaseAgent registers some MIBs by default we need to unregister
    // one before we register our own sysDescr. Normally you would
    // override that method and register the MIBs that you need
    agent.unregisterManagedObject(agent.getSnmpv2MIB());

    // Register a system description, use one from you product environment
    // to test with
    agent.registerManagedObject(MOCreator.createReadOnly(sysDescr,
            "This Description is set By ShivaSoft"));

    System.out.println("Hello before client");
    // Setup the client to use our newly started agent
    client = new SNMPManager("udp:127.0.0.1/2001");
    client.start();
    // Get back Value which is set
    System.out.println(client.getAsString(sysDescr));
}

}

模拟代理的代码:

    package org.bihe;

    import java.io.File;
    import java.io.IOException;
     



    import org.snmp4j.TransportMapping;
    import org.snmp4j.agent.BaseAgent;
    import org.snmp4j.agent.CommandProcessor;
    import org.snmp4j.agent.DuplicateRegistrationException;
    import org.snmp4j.agent.MOGroup;
    import org.snmp4j.agent.ManagedObject;
    import org.snmp4j.agent.mo.MOTableRow;
    import org.snmp4j.agent.mo.snmp.RowStatus;
    import org.snmp4j.agent.mo.snmp.SnmpCommunityMIB;
    import org.snmp4j.agent.mo.snmp.SnmpNotificationMIB;
    import org.snmp4j.agent.mo.snmp.SnmpTargetMIB;
    import org.snmp4j.agent.mo.snmp.StorageType;
    import org.snmp4j.agent.mo.snmp.VacmMIB;
    import org.snmp4j.agent.security.MutableVACM;
    import org.snmp4j.mp.MPv3;
    import org.snmp4j.security.SecurityLevel;
    import org.snmp4j.security.SecurityModel;
    import org.snmp4j.security.USM;
    import org.snmp4j.smi.Address;
    import org.snmp4j.smi.GenericAddress;
    import org.snmp4j.smi.Integer32;
    import org.snmp4j.smi.OID;
    import org.snmp4j.smi.OctetString;
    import org.snmp4j.smi.Variable;
    import org.snmp4j.transport.TransportMappings;
     
    public class SNMPAgent extends BaseAgent {
     
        private String address;
     
        /**
         *
         * @param address
         * @throws IOException
         */
        public SNMPAgent(String address) throws IOException {
     
            /**
             * Creates a base agent with boot-counter, config file, and a
             * CommandProcessor for processing SNMP requests. Parameters:
             * "bootCounterFile" - a file with serialized boot-counter information
             * (read/write). If the file does not exist it is created on shutdown of
             * the agent. "configFile" - a file with serialized configuration
             * information (read/write). If the file does not exist it is created on
             * shutdown of the agent. "commandProcessor" - the CommandProcessor
             * instance that handles the SNMP requests.
             */

            
            super(new File("conf.agent"), new File("bootCounter.agent"),
                    new CommandProcessor(
                            new OctetString(MPv3.createLocalEngineID())));
            this.address = address;
        }
     
        /**
         * Adds community to security name mappings needed for SNMPv1 and SNMPv2c.
         * */
        @SuppressWarnings("unchecked")
        @Override
        protected void addCommunities(SnmpCommunityMIB communityMIB) {
            OID testOct = new OctetString("public2public").toSubIndex(true);
            
            Variable[] com2sec = new Variable[] { new OctetString("public"),
                    new OctetString("cpublic"), // security name
                    getAgent().getContextEngineID(), // local engine ID
                    new OctetString("public"), // default context name
                    new Integer32(StorageType.nonVolatile), // storage type
                    new Integer32(RowStatus.active) // row status
            };
            @SuppressWarnings("rawtypes")
            //After the createRow function is called the variable, "row" is assigned to null
            //due to the aformentioned DefaultMOTable class function, "createRow" 
            MOTableRow row = communityMIB.getSnmpCommunityEntry().createRow(
                    testOct.toSubIndex(true), com2sec);
            /*
            MOTableRow row = communityMIB.getSnmpCommunityEntry().createRow(
                    new OctetString("public2public").toSubIndex(true), com2sec);
                    */
                    
            communityMIB.getSnmpCommunityEntry().addRow(row);
     
        }
     
        /**
         * Adds initial notification targets and filters.
         */
        @Override
        protected void addNotificationTargets(SnmpTargetMIB arg0,
                SnmpNotificationMIB arg1) {
            // TODO Auto-generated method stub
     
        }
     
        /**
         * Adds all the necessary initial users to the USM.
         */
        @Override
        protected void addUsmUser(USM arg0) {
            // TODO Auto-generated method stub
     
        }
     
        /**
         * Adds initial VACM configuration.
         */
        @Override
        protected void addViews(VacmMIB vacm) {
            vacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv2c, new OctetString(
                    "cpublic"), new OctetString("v1v2group"),
                    StorageType.nonVolatile);
     
            vacm.addAccess(new OctetString("v1v2group"), new OctetString("public"),
                    SecurityModel.SECURITY_MODEL_ANY, SecurityLevel.NOAUTH_NOPRIV,
                    MutableVACM.VACM_MATCH_EXACT, new OctetString("fullReadView"),
                    new OctetString("fullWriteView"), new OctetString(
                            "fullNotifyView"), StorageType.nonVolatile);
     
            vacm.addViewTreeFamily(new OctetString("fullReadView"), new OID("1.3"),
                    new OctetString(), VacmMIB.vacmViewIncluded,
                    StorageType.nonVolatile);
     
        }
     
        /**
         * Unregister the basic MIB modules from the agent's MOServer.
         */
        @Override
        protected void unregisterManagedObjects() {
            // TODO Auto-generated method stub
     
        }
     
        /**
         * Register additional managed objects at the agent's server.
         */
        @Override
        protected void registerManagedObjects() {
            // TODO Auto-generated method stub
     
        }
     
        @SuppressWarnings("rawtypes")
        protected void initTransportMappings() throws IOException {
            transportMappings = new TransportMapping[1];
            Address addr = GenericAddress.parse(address);
            TransportMapping tm = TransportMappings.getInstance()
                    .createTransportMapping(addr);
            transportMappings[0] = tm;
        }
     
        /**
         * Start method invokes some initialization methods needed to start the
         * agent
         *
         * @throws IOException
         */
        public void start() throws IOException {
     
            init();
            // This method reads some old config from a file and causes
            // unexpected behavior.
            // loadConfig(ImportModes.REPLACE_CREATE);
            addShutdownHook();
            getServer().addContext(new OctetString("public"));
            finishInit();
            run();
            sendColdStartNotification();
        }
     
        /**
         * Clients can register the MO they need
         */
        public void registerManagedObject(ManagedObject mo) {
            try {
                server.register(mo, null);
            } catch (DuplicateRegistrationException ex) {
                throw new RuntimeException(ex);
            }
        }
     
        public void unregisterManagedObject(MOGroup moGroup) {
            moGroup.unregisterMOs(server, getContext(moGroup));
        }
    }

如果您希望将代码提供给MOCreator或SNMPManager类,我可以提供,但其与“ https://www.jitendrazaa.com/blog/java/snmp/creating-snmp-代理服务器在Java中使用snmp4j /“

编辑: 找到与错误有关的更多信息:

  /**
* The specified object does not exists and presently it cannot be  created,
* see error index.
*/
 public static final int inconsistentName =
   SnmpConstants.SNMP_ERROR_INCONSISTENT_NAME;

0 个答案:

没有答案