📄 simplesnmp.java
字号:
boolean timedOut = false; try { if (getNext) { if (getAll) { // Do our own subtree walk routine, to avoid a known bug in drexel snmp var = new SNMPVarBindList(); String nextoid = baseOid; while (true) { SNMPVarBindList nextpair = comInterface.getNextMIBEntry(nextoid); SNMPObject snmpobj = nextpair.getSNMPObjectAt(0); if (snmpobj instanceof SNMPNull) break; SNMPSequence pair = (SNMPSequence)snmpobj; SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)pair.getSNMPObjectAt(0); nextoid = snmpOID.toString(); if (!nextoid.startsWith(baseOid) || nextoid.equals(baseOid)) break; var.addSNMPObject(pair); } } else { var = new SNMPVarBindList(); String nextoid = baseOid; for (int i=0; i < getCnt; i++) { SNMPVarBindList nextpair = comInterface.getNextMIBEntry(nextoid); SNMPObject snmpobj = nextpair.getSNMPObjectAt(0); if (snmpobj instanceof SNMPNull) break; SNMPSequence pair = (SNMPSequence)snmpobj; SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)pair.getSNMPObjectAt(0); nextoid = snmpOID.toString(); var.addSNMPObject(pair); } } } else { var = comInterface.getMIBEntry(baseOid); } } catch (SocketTimeoutException exp) { timedOut = true; } catch (SNMPBadValueException exp) { System.err.println("SNMPBadValueException: " + exp); return l; } catch (SNMPException exp) { if (!(exp instanceof SNMPGetException && exp.getMessage() != null && exp.getMessage().indexOf("not available for retrieval") >= 0)) { System.err.println("SNMPException: " + exp); } return l; } if (timedOut) { timeoutCnt++; if (timeoutCnt >= retries) { throw new TimeoutException("Timed out " + timeoutCnt + " times, giving up"); } else { // Re-try operation, but back off on the timeout value return getAllJavaSnmp(baseOid, getCnt, decodeHex, getNext, stripPrefix, stripCnt, timeout*backoff); } } timeoutCnt = 0; for (int i=0; i < var.size(); i++) { SNMPSequence pair = (SNMPSequence)(var.getSNMPObjectAt(i)); SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)pair.getSNMPObjectAt(0); SNMPObject snmpValue = pair.getSNMPObjectAt(1); String oid = snmpOID.toString(); String data; if (!decodeHex && snmpValue instanceof SNMPOctetString) { data = toHexString((byte[])snmpValue.getValue()); } else { data = snmpValue.toString(); } data = data.trim(); if (data.length() == 0 && !(snmpValue instanceof SNMPOctetString)) { // Skip empty variables which are not strings continue; } String strippedOid = stripPrefix && oid.startsWith(baseOid) ? oid.substring(baseOid.length()) : oid; String[] s = { strippedOid.length() > 0 && strippedOid.charAt(0) == '.' ? strippedOid.substring(1) : strippedOid, data }; s[0] = strip(s[0], '.', stripCnt, true); l.add(s); } } catch (IOException e) { outl(" *ERROR*: Host: " + host + " IOException: " + e.getMessage() ); e.printStackTrace(System.err); } getCnt = 0; return l; } private String toHexString(byte[] bytes) { StringBuffer sb = new StringBuffer(); int[] ints = new int[bytes.length]; for (int i=0; i < ints.length; i++) ints[i] = bytes[i] < 0 ? 256 + bytes[i] : bytes[i]; for (int i=0; i < ints.length; i++) sb.append((i>0?":":"")+(ints[i]<16?"0":"")+Integer.toString(ints[i], 16)); return sb.toString(); } private ArrayList getAllWesthawk(String baseOid, int getCnt, boolean decodeHex, boolean getNext, int stripCnt) throws TimeoutException { ArrayList l = new ArrayList(); /* try { checkSnmpContext(); BlockPdu pdu = new BlockPdu(context); pdu.addOid(baseOid); pdu.setPduType(getNext ? BlockPdu.GETNEXT : BlockPdu.GET); boolean sentGetNext = getNext; String oid = baseOid; // Should we get the entire subtree? boolean getAll = getCnt == 0; while (true) { try { varbind vb; while ( (vb=pdu.getResponseVariableBinding()) != null) { oid = vb.getOid().getValue(); if (!baseOid.equals(oid) && !oid.startsWith(baseOid+".")) break; // Reset timeoutCnt timeoutCnt = 0; // Behandle svaret vi har fått String data; { AsnObject o = vb.getValue(); if (o instanceof AsnOctets) { AsnOctets ao = (AsnOctets)o; data = (decodeHex ? ao.toDisplayString() : ao.toHex()); //outl("OID: " + oid + " S: " + data + " HEX: " + ao.toHex() ); } else { data = o.toString(); } data = data.trim(); } //outl("Base: " + baseOid); //outl("Oid : " + oid); // If the returned OID is of greater length than the baseOid, remove the baseOid prefix; // otherwise, use the empty string String[] s = { oid.length() == baseOid.length() ? "" : oid.substring(baseOid.length()+1, oid.length()), data.trim() }; s[0] = strip(s[0], '.', stripCnt, true); l.add(s); if (!getAll && --getCnt == 0) break; pdu = new BlockPdu(context); pdu.setPduType(BlockPdu.GETNEXT); pdu.addOid(oid); if (getNextDelay > 0) { try { //System.err.println("Sleeping " + getNextDelay + " ms."); Thread.currentThread().sleep(getNextDelay); } catch (InterruptedException e) { } } } } catch (PduException e) { String m = e.getMessage(); if (m.equals("No such name error")) { if (!sentGetNext) { pdu = new BlockPdu(context); pdu.setPduType(BlockPdu.GETNEXT); pdu.addOid(oid); sentGetNext = true; continue; } } else if (m.equals("Timed out")) { gotTimeout = true; timeoutCnt++; if (timeoutCnt >= timeoutLimit) { throw new TimeoutException("Too many timeouts, giving up"); } else { // Re-try operation continue; } } else { outl(" *ERROR*: Host: " + host + " PduExecption: " + e.getMessage() ); } } // Ferdig å hente meldinger break; } // while } catch (IOException e) { outl(" *ERROR*: Host: " + host + " IOException: " + e.getMessage() ); } */ getCnt = 0; return l; } /** * Check if the SnmpContext is still valid and update it if necessary. * * @return true if the SnmpContext was updated */ protected boolean checkSnmpContext() throws IOException { if (comInterface == null || !valid) { if (comInterface != null) comInterface.closeConnection(); InetAddress hostAddress = InetAddress.getByName(host); comInterface = new SNMPv1CommunicationInterface(snmpVersion, hostAddress, cs_ro); if (this.socketTimeout > 0) comInterface.setSocketTimeout(this.socketTimeout); timeoutCnt = 0; valid = true; return true; } return false; } /** * Check if the SnmpContext is still valid and update it if necessary. * * @return true if the SnmpContext was updated */ /* protected boolean checkSnmpContext2() throws IOException { if (context == null || !context.getHost().equals(host)) { if (context != null) context.destroy(); //Exception e = new Exception("["+super.toString()+"] ["+Integer.toHexString(Thread.currentThread().hashCode())+"]"); //e.printStackTrace(System.err); context = new SnmpContext(host, 161); //System.err.println("+++Creating context: " + context); context.setCommunity(cs_ro); timeoutCnt = 0; return true; } else if (!context.getCommunity().equals(cs_ro)) { context.setCommunity(cs_ro); } return false; } */ /** * Deallocate any resources used. */ public void destroy() { if (comInterface != null) { try { comInterface.closeConnection(); } catch (SocketException exp) { } comInterface = null; } } /** * Deallocate any resources used. */ /* public void destroy2() { //Exception e = new Exception("["+super.toString()+"] ["+Integer.toHexString(Thread.currentThread().hashCode())+"]: " + context); //e.printStackTrace(System.err); if (context != null) { //System.err.println("---Destroying context: " + context); context.destroy(); context = null; } } */ /** * Check which version of SNMP the active device supports and set it active. */ public int checkSnmpVersion() { // First we check if the device can support SNMPv2 onlyAskModule("0"); setSnmpVersion(2); int snmpVersion = 1; try { getNext("1", 1, false, true); snmpVersion = 2; } catch (Exception e) { setSnmpVersion(1); } finally { onlyAskModule(null); } return snmpVersion; } public void finalize() { destroy(); } private static void out(String s) { System.out.print(s); } private static void outl(String s) { System.out.println(s); } private static void err(String s) { System.err.print(s); } private static void errl(String s) { System.err.println(s); } /** * @return The backoff factor * @see #setBackoff(int) */ public int getBackoff() { return backoff; } /** * Sets the backoff factor for retries. * * <p>Whenever a request times out, the timeout limit * of each retry attempt will be multiplied by this factor. * If set to 1, no timeout backoff will occur.</p> * * <p>The default factor is 2.</p> * * @param backoff An integer backoff factor. */ public void setBackoff(int backoff) { this.backoff = backoff; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -