{"id":1576,"date":"2011-02-24T00:14:18","date_gmt":"2011-02-23T18:44:18","guid":{"rendered":"http:\/\/JitendraZaa.com\/blog\/?p=1576"},"modified":"2015-03-24T17:18:07","modified_gmt":"2015-03-24T17:18:07","slug":"creating-snmp-agent-server-in-java-using-snmp4j","status":"publish","type":"post","link":"https:\/\/www.jitendrazaa.com\/blog\/java\/snmp\/creating-snmp-agent-server-in-java-using-snmp4j\/","title":{"rendered":"Creating SNMP Agent (Server) in JAVA using SNMP4j"},"content":{"rendered":"<p>In Previous article, we have seen that how to <a title=\"Create SNMP Client in JAVA using SNMP4j\" href=\"https:\/\/jitendrazaa.com\/blog\/java\/snmp\/create-snmp-client-in-java-using-snmp4j\/\" target=\"_blank\">create SNMP client in JAVA using SNMP4j<\/a>.<\/p>\n<p style=\"text-align: justify;\">To create the Agent for SNMP which listens for the request should extend the abstract class <strong>BaseAgent<\/strong>.<br \/>\nThe BaseAgent abstract class defines a framework for writing SNMP agents using the <strong>SNMP4J-Agent API<\/strong>. To implement your own SNMP agent, extend this class and implement the abstract methods defined by BaseAgent. The hook methods do not need any specific implementation. They only provide a defined mechanism to customize your agent.<\/p>\n<p><strong><!--more-->Below Class is used to create the SNMP Agent:<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.G2.SNMP.Server;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\n\r\nimport org.snmp4j.TransportMapping;\r\nimport org.snmp4j.agent.BaseAgent;\r\nimport org.snmp4j.agent.CommandProcessor;\r\nimport org.snmp4j.agent.DuplicateRegistrationException;\r\nimport org.snmp4j.agent.MOGroup;\r\nimport org.snmp4j.agent.ManagedObject;\r\nimport org.snmp4j.agent.mo.MOTableRow;\r\nimport org.snmp4j.agent.mo.snmp.RowStatus;\r\nimport org.snmp4j.agent.mo.snmp.SnmpCommunityMIB;\r\nimport org.snmp4j.agent.mo.snmp.SnmpNotificationMIB;\r\nimport org.snmp4j.agent.mo.snmp.SnmpTargetMIB;\r\nimport org.snmp4j.agent.mo.snmp.StorageType;\r\nimport org.snmp4j.agent.mo.snmp.VacmMIB;\r\nimport org.snmp4j.agent.security.MutableVACM;\r\nimport org.snmp4j.mp.MPv3;\r\nimport org.snmp4j.security.SecurityLevel;\r\nimport org.snmp4j.security.SecurityModel;\r\nimport org.snmp4j.security.USM;\r\nimport org.snmp4j.smi.Address;\r\nimport org.snmp4j.smi.GenericAddress;\r\nimport org.snmp4j.smi.Integer32;\r\nimport org.snmp4j.smi.OID;\r\nimport org.snmp4j.smi.OctetString;\r\nimport org.snmp4j.smi.Variable;\r\nimport org.snmp4j.transport.TransportMappings;\r\n\r\npublic class SNMPAgent extends BaseAgent {\r\n\r\n\tprivate String address;\r\n\r\n\t\/**\r\n\t *\r\n\t * @param address\r\n\t * @throws IOException\r\n\t *\/\r\n\tpublic SNMPAgent(String address) throws IOException {\r\n\r\n\t\t\/**\r\n\t\t * Creates a base agent with boot-counter, config file, and a\r\n\t\t * CommandProcessor for processing SNMP requests. Parameters:\r\n\t\t * &quot;bootCounterFile&quot; - a file with serialized boot-counter information\r\n\t\t * (read\/write). If the file does not exist it is created on shutdown of\r\n\t\t * the agent. &quot;configFile&quot; - a file with serialized configuration\r\n\t\t * information (read\/write). If the file does not exist it is created on\r\n\t\t * shutdown of the agent. &quot;commandProcessor&quot; - the CommandProcessor\r\n\t\t * instance that handles the SNMP requests.\r\n\t\t *\/\r\n\t\tsuper(new File(&quot;conf.agent&quot;), new File(&quot;bootCounter.agent&quot;),\r\n\t\t\t\tnew CommandProcessor(\r\n\t\t\t\t\t\tnew OctetString(MPv3.createLocalEngineID())));\r\n\t\tthis.address = address;\r\n\t}\r\n\r\n\t\/**\r\n\t * Adds community to security name mappings needed for SNMPv1 and SNMPv2c.\r\n\t *\/\r\n\t@Override\r\n\tprotected void addCommunities(SnmpCommunityMIB communityMIB) {\r\n\t\tVariable&#x5B;] com2sec = new Variable&#x5B;] { new OctetString(&quot;public&quot;),\r\n\t\t\t\tnew OctetString(&quot;cpublic&quot;), \/\/ security name\r\n\t\t\t\tgetAgent().getContextEngineID(), \/\/ local engine ID\r\n\t\t\t\tnew OctetString(&quot;public&quot;), \/\/ default context name\r\n\t\t\t\tnew OctetString(), \/\/ transport tag\r\n\t\t\t\tnew Integer32(StorageType.nonVolatile), \/\/ storage type\r\n\t\t\t\tnew Integer32(RowStatus.active) \/\/ row status\r\n\t\t};\r\n\t\tMOTableRow row = communityMIB.getSnmpCommunityEntry().createRow(\r\n\t\t\t\tnew OctetString(&quot;public2public&quot;).toSubIndex(true), com2sec);\r\n\t\tcommunityMIB.getSnmpCommunityEntry().addRow(row);\r\n\r\n\t}\r\n\r\n\t\/**\r\n\t * Adds initial notification targets and filters.\r\n\t *\/\r\n\t@Override\r\n\tprotected void addNotificationTargets(SnmpTargetMIB arg0,\r\n\t\t\tSnmpNotificationMIB arg1) {\r\n\t\t\/\/ TODO Auto-generated method stub\r\n\r\n\t}\r\n\r\n\t\/**\r\n\t * Adds all the necessary initial users to the USM.\r\n\t *\/\r\n\t@Override\r\n\tprotected void addUsmUser(USM arg0) {\r\n\t\t\/\/ TODO Auto-generated method stub\r\n\r\n\t}\r\n\r\n\t\/**\r\n\t * Adds initial VACM configuration.\r\n\t *\/\r\n\t@Override\r\n\tprotected void addViews(VacmMIB vacm) {\r\n\t\tvacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv2c, new OctetString(\r\n\t\t\t\t&quot;cpublic&quot;), new OctetString(&quot;v1v2group&quot;),\r\n\t\t\t\tStorageType.nonVolatile);\r\n\r\n\t\tvacm.addAccess(new OctetString(&quot;v1v2group&quot;), new OctetString(&quot;public&quot;),\r\n\t\t\t\tSecurityModel.SECURITY_MODEL_ANY, SecurityLevel.NOAUTH_NOPRIV,\r\n\t\t\t\tMutableVACM.VACM_MATCH_EXACT, new OctetString(&quot;fullReadView&quot;),\r\n\t\t\t\tnew OctetString(&quot;fullWriteView&quot;), new OctetString(\r\n\t\t\t\t\t\t&quot;fullNotifyView&quot;), StorageType.nonVolatile);\r\n\r\n\t\tvacm.addViewTreeFamily(new OctetString(&quot;fullReadView&quot;), new OID(&quot;1.3&quot;),\r\n\t\t\t\tnew OctetString(), VacmMIB.vacmViewIncluded,\r\n\t\t\t\tStorageType.nonVolatile);\r\n\r\n\t}\r\n\r\n\t\/**\r\n\t * Unregister the basic MIB modules from the agent's MOServer.\r\n\t *\/\r\n\t@Override\r\n\tprotected void unregisterManagedObjects() {\r\n\t\t\/\/ TODO Auto-generated method stub\r\n\r\n\t}\r\n\r\n\t\/**\r\n\t * Register additional managed objects at the agent's server.\r\n\t *\/\r\n\t@Override\r\n\tprotected void registerManagedObjects() {\r\n\t\t\/\/ TODO Auto-generated method stub\r\n\r\n\t}\r\n\r\n\tprotected void initTransportMappings() throws IOException {\r\n\t\ttransportMappings = new TransportMapping&#x5B;1];\r\n\t\tAddress addr = GenericAddress.parse(address);\r\n\t\tTransportMapping tm = TransportMappings.getInstance()\r\n\t\t\t\t.createTransportMapping(addr);\r\n\t\ttransportMappings&#x5B;0] = tm;\r\n\t}\r\n\r\n\t\/**\r\n\t * Start method invokes some initialization methods needed to start the\r\n\t * agent\r\n\t *\r\n\t * @throws IOException\r\n\t *\/\r\n\tpublic void start() throws IOException {\r\n\r\n\t\tinit();\r\n\t\t\/\/ This method reads some old config from a file and causes\r\n\t\t\/\/ unexpected behavior.\r\n\t\t\/\/ loadConfig(ImportModes.REPLACE_CREATE);\r\n\t\taddShutdownHook();\r\n\t\tgetServer().addContext(new OctetString(&quot;public&quot;));\r\n\t\tfinishInit();\r\n\t\trun();\r\n\t\tsendColdStartNotification();\r\n\t}\r\n\r\n\t\/**\r\n\t * Clients can register the MO they need\r\n\t *\/\r\n\tpublic void registerManagedObject(ManagedObject mo) {\r\n\t\ttry {\r\n\t\t\tserver.register(mo, null);\r\n\t\t} catch (DuplicateRegistrationException ex) {\r\n\t\t\tthrow new RuntimeException(ex);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void unregisterManagedObject(MOGroup moGroup) {\r\n\t\tmoGroup.unregisterMOs(server, getContext(moGroup));\r\n\t}\r\n\r\n}\r\n<\/pre>\n<p><strong> This class is used to create ManagedObject which is used by the SNMP agent Class created above:<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.G2.SNMP.Server;\r\n\r\nimport org.snmp4j.agent.mo.MOAccessImpl;\r\nimport org.snmp4j.agent.mo.MOScalar;\r\nimport org.snmp4j.smi.OID;\r\nimport org.snmp4j.smi.OctetString;\r\nimport org.snmp4j.smi.Variable;\r\n\r\n\/**\r\n * This class creates and returns ManagedObjects\r\n * @author Shiva\r\n *\r\n *\/\r\npublic class MOCreator {\r\n\tpublic static MOScalar createReadOnly(OID oid,Object value ){\r\n\t\treturn new MOScalar(oid,\r\n\t\t\t\tMOAccessImpl.ACCESS_READ_ONLY,\r\n\t\t\t\tgetVariable(value));\r\n\t}\r\n\r\n\tprivate static Variable getVariable(Object value) {\r\n\t\tif(value instanceof String) {\r\n\t\t\treturn new OctetString((String)value);\r\n\t\t}\r\n\t\tthrow new IllegalArgumentException(&quot;Unmanaged Type: &quot; + value.getClass());\r\n\t}\r\n\r\n}\r\n<\/pre>\n<p><strong> Below class tests that agent is working properly or not :<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.G2.SNMP.Server;\r\n\r\nimport java.io.IOException;\r\n\r\nimport org.snmp4j.smi.OID;\r\n\r\nimport com.G2.SNMP.client.SNMPManager;\r\n\r\npublic class TestSNMPAgent {\r\n\r\n\tstatic final OID sysDescr = new OID(&quot;.1.3.6.1.2.1.1.1.0&quot;);\r\n\r\n\tpublic static void main(String&#x5B;] args) throws IOException {\r\n\t\tTestSNMPAgent client = new TestSNMPAgent(&quot;udp:127.0.0.1\/161&quot;);\r\n\t\tclient.init();\r\n\t}\r\n\r\n\tSNMPAgent agent = null;\r\n\t\/**\r\n\t * This is the client which we have created earlier\r\n\t *\/\r\n\tSNMPManager client = null;\r\n\r\n\tString address = null;\r\n\r\n\t\/**\r\n\t * Constructor\r\n\t *\r\n\t * @param add\r\n\t *\/\r\n\tpublic TestSNMPAgent(String add) {\r\n\t\taddress = add;\r\n\t}\r\n\r\n\tprivate void init() throws IOException {\r\n\t\tagent = new SNMPAgent(&quot;0.0.0.0\/2001&quot;);\r\n\t\tagent.start();\r\n\r\n\t\t\/\/ Since BaseAgent registers some MIBs by default we need to unregister\r\n\t\t\/\/ one before we register our own sysDescr. Normally you would\r\n\t\t\/\/ override that method and register the MIBs that you need\r\n\t\tagent.unregisterManagedObject(agent.getSnmpv2MIB());\r\n\r\n\t\t\/\/ Register a system description, use one from you product environment\r\n\t\t\/\/ to test with\r\n\t\tagent.registerManagedObject(MOCreator.createReadOnly(sysDescr,\r\n\t\t\t\t&quot;This Description is set By ShivaSoft&quot;));\r\n\r\n\t\t\/\/ Setup the client to use our newly started agent\r\n\t\tclient = new SNMPManager(&quot;udp:127.0.0.1\/2001&quot;);\r\n\t\tclient.start();\r\n\t\t\/\/ Get back Value which is set\r\n\t\tSystem.out.println(client.getAsString(sysDescr));\r\n\t}\r\n\r\n}\r\n<\/pre>\n<p><strong> Output :<\/strong><\/p>\n<blockquote><p>This Description is set By ShivaSoft<\/p><\/blockquote>\n<p><strong>Possible run time errors :<\/strong><br \/>\nFew of you may receive error like<\/p>\n<blockquote><p>&#8220;Exception in thread &#8220;main&#8221; java.lang.RuntimeException: java.net.BindException: Address already in use: Cannot bind&#8221;.<\/p><\/blockquote>\n<p><strong>Solution:<\/strong> You are trying to listen on a local IP and port which is already in use by some other process (for example the operating system &#8211; if you use port 161 this is rather likely).<\/p>\n<p>Try to use a different port (or IP address &#8211; but most services listen on all local IP addresses) or stop the process that is using it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Creating SNMP Agent (Server) in JAVA using SNMP4j<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"jz_research_post":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[12],"tags":[329,183],"class_list":["post-1576","post","type-post","status-publish","format-standard","hentry","category-snmp","tag-java","tag-snmp4j"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":1571,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/snmp\/create-snmp-client-in-java-using-snmp4j\/","url_meta":{"origin":1576,"position":0},"title":"Create SNMP Client in JAVA Using SNMP4j","author":"Jitendra","date":"February 23, 2011","format":false,"excerpt":"Create SNMP Client in JAVA Using SNMP4j","rel":"","context":"In &quot;SNMP&quot;","block_context":{"text":"SNMP","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/snmp\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1582,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/snmp\/generating-trap-in-snmp-using-snmp4j\/","url_meta":{"origin":1576,"position":1},"title":"Generating TRAP in SNMP using SNMP4j","author":"Jitendra","date":"February 24, 2011","format":false,"excerpt":"Generating TRAP in SNMP using SNMP4j","rel":"","context":"In &quot;SNMP&quot;","block_context":{"text":"SNMP","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/snmp\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1554,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/snmp\/terminologies-used-in-snmp\/","url_meta":{"origin":1576,"position":2},"title":"Terminologies used in SNMP","author":"Jitendra","date":"February 23, 2011","format":false,"excerpt":"Terminologies used in SNMP","rel":"","context":"In &quot;SNMP&quot;","block_context":{"text":"SNMP","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/snmp\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1548,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/snmp\/introduction-to-snmp\/","url_meta":{"origin":1576,"position":3},"title":"Introduction to SNMP","author":"Jitendra","date":"February 23, 2011","format":false,"excerpt":"Introduction to SNMP in JAVA","rel":"","context":"In &quot;SNMP&quot;","block_context":{"text":"SNMP","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/snmp\/"},"img":{"alt_text":"Structure of MIB SNMP","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/02\/Structure-of-MIB-SNMP.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1563,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/snmp\/install-snmp-service-in-windows-xp-and-overview-of-mib-explorer\/","url_meta":{"origin":1576,"position":4},"title":"Install SNMP Service in Windows XP and Overview of MIB Explorer","author":"Jitendra","date":"February 23, 2011","format":false,"excerpt":"Install SNMP Service in Windows XP and Overview of MIB Explorer","rel":"","context":"In &quot;SNMP&quot;","block_context":{"text":"SNMP","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/snmp\/"},"img":{"alt_text":"Install SNMP Service in Windows XP","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/02\/Install-SNMP-Service-in-Windows-XP.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1764,"url":"https:\/\/www.jitendrazaa.com\/blog\/java\/read-xml-file-using-sax-parser-in-java\/","url_meta":{"origin":1576,"position":5},"title":"Read XML File using SAX Parser in JAVA","author":"Jitendra","date":"March 22, 2011","format":false,"excerpt":"Example of Reading XML File using SAX Parser in JAVA","rel":"","context":"In &quot;JAVA&quot;","block_context":{"text":"JAVA","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/java\/"},"img":{"alt_text":"SAX Parser","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2011\/03\/SAX-Parser.jpg?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1576","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/comments?post=1576"}],"version-history":[{"count":2,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1576\/revisions"}],"predecessor-version":[{"id":4353,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/1576\/revisions\/4353"}],"wp:attachment":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/media?parent=1576"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/categories?post=1576"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/tags?post=1576"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}