Guest User

Untitled

a guest
Jun 25th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.28 KB | None | 0 0
  1. public class SNMPManager {
  2.  
  3. Snmp snmp = null;
  4. String address = null;
  5.  
  6. /**
  7. * Constructor
  8. *
  9. * @param add
  10. */
  11. public SNMPManager(String add) {
  12. address = add;
  13. }
  14.  
  15. public static void main(String[] args) throws IOException {
  16. /**
  17. * Port 161 is used for Read and Other operations Port 162 is used for the trap
  18. * generation
  19. */
  20. SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
  21. client.start();
  22. /**
  23. * OID - .1.3.6.1.2.1.1.1.0 => SysDec OID - .1.3.6.1.2.1.1.5.0 => SysName => MIB
  24. * explorer will be usefull here, as discussed in previous article
  25. */
  26. String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
  27. System.out.println(sysDescr);
  28. }
  29.  
  30. /**
  31. * Start the Snmp session. If you forget the listen() method you will not get
  32. * any answers because the communication is asynchronous and the listen() method
  33. * listens for answers.
  34. *
  35. * @throws IOException
  36. */
  37. public void start() throws IOException {
  38. TransportMapping<?> transport = new DefaultUdpTransportMapping();
  39. snmp = new Snmp(transport);
  40. // Do not forget this line!
  41. transport.listen();
  42. }
  43.  
  44. /**
  45. * Method which takes a single OID and returns the response from the agent as a
  46. * String.
  47. *
  48. * @param oid
  49. * @return
  50. * @throws IOException
  51. */
  52. public String getAsString(OID oid) throws IOException {
  53. ResponseEvent event = get(new OID[] { oid });
  54. return event.getResponse().get(0).getVariable().toString();
  55. }
  56.  
  57. /**
  58. * This method is capable of handling multiple OIDs
  59. *
  60. * @param oids
  61. * @return
  62. * @throws IOException
  63. */
  64. public ResponseEvent get(OID oids[]) throws IOException {
  65. PDU pdu = new PDU();
  66. for (OID oid : oids) {
  67. pdu.add(new VariableBinding(oid));
  68. }
  69. pdu.setType(PDU.GET);
  70. ResponseEvent event = snmp.send(pdu, getTarget(), null);
  71. if (event != null) {
  72. return event;
  73. }
  74. throw new RuntimeException("GET timed out");
  75. }
  76.  
  77. public ResponseEvent set(OID oid, String val) throws IOException {
  78. PDU pdu = new PDU();
  79. VariableBinding varBind = new VariableBinding(oid, new OctetString(val));
  80. pdu.add(varBind);
  81. pdu.setType(PDU.SET);
  82. //pdu.setRequestID(new Integer32(1));
  83. Target target = getTarget();
  84.  
  85. ResponseEvent event = snmp.set(pdu, target);
  86. if (event != null) {
  87. System.out.println("nResponse:nGot Snmp Set Response from Agent");
  88. System.out.println("Snmp Set Request = " + event.getRequest().getVariableBindings());
  89. PDU responsePDU = event.getResponse();
  90. System.out.println("nresponsePDU = " + responsePDU);
  91. if (responsePDU != null) {
  92. int errorStatus = responsePDU.getErrorStatus();
  93. int errorIndex = responsePDU.getErrorIndex();
  94. String errorStatusText = responsePDU.getErrorStatusText();
  95. System.out.println("nresponsePDU = " + responsePDU);
  96. if (errorStatus == PDU.noError) {
  97. System.out.println("Snmp Set Response = " + responsePDU.getVariableBindings());
  98. } else {
  99. System.out.println("errorStatus = " + responsePDU);
  100. System.out.println("Error: Request Failed");
  101. System.out.println("Error Status = " + errorStatus);
  102. System.out.println("Error Index = " + errorIndex);
  103. System.out.println("Error Status Text = " + errorStatusText);
  104. }
  105. }
  106.  
  107. return event;
  108. }
  109. throw new RuntimeException("SET timed out");
  110. }
  111.  
  112. /**
  113. * This method returns a Target, which contains information about where the data
  114. * should be fetched and how.
  115. *
  116. * @return
  117. */
  118. private Target getTarget() {
  119. Address targetAddress = GenericAddress.parse(address);
  120. CommunityTarget target = new CommunityTarget();
  121. target.setCommunity(new OctetString("public"));
  122. target.setAddress(targetAddress);
  123. target.setRetries(2);
  124. target.setTimeout(1500);
  125. target.setVersion(SnmpConstants.version2c);
  126. return target;
  127. }
  128. }
  129.  
  130. public class SNMPAgent extends BaseAgent {
  131.  
  132. private String address;
  133.  
  134. /**
  135. *
  136. * @param address
  137. * @throws IOException
  138. */
  139. public SNMPAgent(String address) throws IOException {
  140.  
  141. /**
  142. * Creates a base agent with boot-counter, config file, and a CommandProcessor
  143. * for processing SNMP requests. Parameters: "bootCounterFile" - a file with
  144. * serialized boot-counter information (read/write). If the file does not exist
  145. * it is created on shutdown of the agent. "configFile" - a file with serialized
  146. * configuration information (read/write). If the file does not exist it is
  147. * created on shutdown of the agent. "commandProcessor" - the CommandProcessor
  148. * instance that handles the SNMP requests.
  149. */
  150. super(new File("conf.agent"), new File("bootCounter.agent"),
  151. new CommandProcessor(new OctetString(MPv3.createLocalEngineID())));
  152. this.address = address;
  153. }
  154.  
  155. /**
  156. * Adds community to security name mappings needed for SNMPv1 and SNMPv2c.
  157. */
  158. @Override
  159. protected void addCommunities(SnmpCommunityMIB communityMIB) {
  160. Variable[] com2sec = new Variable[] { new OctetString("public"), new OctetString("cpublic"), // security name
  161. getAgent().getContextEngineID(), // local engine ID
  162. new OctetString("public"), // default context name
  163. new OctetString(), // transport tag
  164. new Integer32(StorageType.nonVolatile), // storage type
  165. new Integer32(RowStatus.active) // row status
  166. };
  167. MOTableRow<?> row = communityMIB.getSnmpCommunityEntry()
  168. .createRow(new OctetString("public2public").toSubIndex(true), com2sec);
  169. communityMIB.getSnmpCommunityEntry().addRow((SnmpCommunityEntryRow) row);
  170.  
  171. }
  172.  
  173. /**
  174. * Adds initial notification targets and filters.
  175. */
  176. @Override
  177. protected void addNotificationTargets(SnmpTargetMIB arg0, SnmpNotificationMIB arg1) {
  178. // TODO Auto-generated method stub
  179.  
  180. }
  181.  
  182. /**
  183. * Adds all the necessary initial users to the USM.
  184. */
  185. @Override
  186. protected void addUsmUser(USM arg0) {
  187. // TODO Auto-generated method stub
  188.  
  189. }
  190.  
  191. /**
  192. * Adds initial VACM configuration.
  193. */
  194. @Override
  195. protected void addViews(VacmMIB vacm) {
  196. vacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv2c, new OctetString("cpublic"), new OctetString("v1v2group"),
  197. StorageType.nonVolatile);
  198.  
  199. vacm.addAccess(new OctetString("v1v2group"), new OctetString("public"), SecurityModel.SECURITY_MODEL_ANY,
  200. SecurityLevel.NOAUTH_NOPRIV, MutableVACM.VACM_MATCH_EXACT, new OctetString("fullReadView"),
  201. new OctetString("fullWriteView"), new OctetString("fullNotifyView"), StorageType.nonVolatile);
  202.  
  203. vacm.addViewTreeFamily(new OctetString("fullReadView"), new OID("1.3"), new OctetString(),
  204. VacmMIB.vacmViewIncluded, StorageType.nonVolatile);
  205.  
  206.  
  207. }
  208.  
  209. /**
  210. * Unregister the basic MIB modules from the agent's MOServer.
  211. */
  212. @Override
  213. protected void unregisterManagedObjects() {
  214. // TODO Auto-generated method stub
  215.  
  216. }
  217.  
  218. /**
  219. * Register additional managed objects at the agent's server.
  220. */
  221. @Override
  222. protected void registerManagedObjects() {
  223. // TODO Auto-generated method stub
  224.  
  225. }
  226.  
  227. @SuppressWarnings("unchecked")
  228. protected void initTransportMappings() throws IOException {
  229. transportMappings = new TransportMapping[1];
  230. Address addr = GenericAddress.parse(address);
  231. TransportMapping<?> tm = TransportMappings.getInstance().createTransportMapping(addr);
  232. transportMappings[0] = tm;
  233. }
  234.  
  235. /**
  236. * Start method invokes some initialization methods needed to start the agent
  237. *
  238. * @throws IOException
  239. */
  240. public void start() throws IOException {
  241.  
  242. init();
  243. // This method reads some old config from a file and causes
  244. // unexpected behavior.
  245. // loadConfig(ImportModes.REPLACE_CREATE);
  246. addShutdownHook();
  247. getServer().addContext(new OctetString("public"));
  248. finishInit();
  249. run();
  250. sendColdStartNotification();
  251. }
  252.  
  253. /**
  254. * Clients can register the MO they need
  255. */
  256. public void registerManagedObject(ManagedObject mo) {
  257. try {
  258. server.register(mo, null);
  259. } catch (DuplicateRegistrationException ex) {
  260. throw new RuntimeException(ex);
  261. }
  262. }
  263.  
  264. public void unregisterManagedObject(MOGroup moGroup) {
  265. moGroup.unregisterMOs(server, getContext(moGroup));
  266. }
  267.  
  268. }
  269.  
  270. public class MOCreator {
  271. public static MOScalar<Variable> createReadOnly(OID oid,Object value ){
  272. return new MOScalar<Variable>(oid,
  273. MOAccessImpl.ACCESS_READ_WRITE,
  274. getVariable(value));
  275. }
  276.  
  277. private static Variable getVariable(Object value) {
  278. if(value instanceof String) {
  279. return new OctetString((String)value);
  280. }
  281. throw new IllegalArgumentException("Unmanaged Type: " + value.getClass());
  282. }
  283.  
  284. }
  285.  
  286. public class TestSNMPAgent {
  287. String siteOIDNumber = "1";
  288. String dataOIDNumber = "1";
  289. String sensorOIDNumber = "1";
  290. OID newOIDdata = new OID("1.3.6.1.4.1.1234.5." + siteOIDNumber + ".2." + dataOIDNumber + "." + sensorOIDNumber + ".0");
  291. OID newOIDdata2 = new OID("1.3.6.1.4.1.1234.5.1.2.1.2.0");
  292. OID newOIDdata3 = new OID("1.3.6.1.4.1.1234.5.1.2.1.3.0");
  293.  
  294. public static void main(String[] args) throws IOException {
  295. TestSNMPAgent client = new TestSNMPAgent("udp:127.0.0.1/161");
  296. client.init();
  297. }
  298.  
  299. SNMPAgent agent = null;
  300. /**
  301. * This is the client which we have created earlier
  302. */
  303. SNMPManager client = null;
  304.  
  305. String address = null;
  306.  
  307. /**
  308. * Constructor
  309. *
  310. * @param add
  311. */
  312. public TestSNMPAgent(String add) {
  313. address = add;
  314. }
  315.  
  316. /**
  317. * Initiates the testing of the SNMP Agent.
  318. * @throws IOException
  319. */
  320. private void init() throws IOException {
  321. /*agent = new SNMPAgent("172.21.1.103/2001");*/
  322. agent = new SNMPAgent("172.21.1.103/2010");
  323. agent.start();
  324.  
  325. // Since BaseAgent registers some MIBs by default we need to unregister
  326. // one before we register our own sysDescr. Normally you would
  327. // override that method and register the MIBs that you need
  328. agent.unregisterManagedObject(agent.getSnmpv2MIB());
  329. //agent.registerManagedObject(MOCreator.createReadOnly(sysDescr,"This Description is set By KGrewe"));
  330. agent.registerManagedObject(MOCreator.createReadOnly(newOIDdata, "50"));
  331. agent.registerManagedObject(MOCreator.createReadOnly(newOIDdata2, "NaN"));
  332. agent.registerManagedObject(MOCreator.createReadOnly(newOIDdata3, "3"));
  333. SNMPManager client1 = new SNMPManager("udp:127.21.1.103/2010");
  334. client1.start();
  335. client1.set(newOIDdata, "30");
  336. //System.out.println(newOIDdata);
  337. // Get back Value which is set
  338. //System.out.println(client1.getAsString(newOIDdata));
  339. while(true) {
  340.  
  341. }
  342.  
  343. }
  344.  
  345. }
Add Comment
Please, Sign In to add comment