📄 simplesnmp.java
字号:
/** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll() throws TimeoutException { return getAll(false, true); } /** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @param baseOid Override the baseOid; if null a null value is returned * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll(String baseOid) throws TimeoutException { return getAll(baseOid, false, true); } /** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @param decodeHex Try to decode returned hex to ASCII * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll(boolean decodeHex) throws TimeoutException { return getAll(decodeHex, true); } /** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @param baseOid Override the baseOid; if null a null value is returned * @param decodeHex Try to decode returned hex to ASCII * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll(String baseOid, boolean decodeHex) throws TimeoutException { return getAll(baseOid, decodeHex, true); } /** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @param baseOid Override the baseOid; if null a null value is returned * @param decodeHex Try to decode returned hex to ASCII * @param stripCnt Strip this many elements (separated by .) from the start of OIDs * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll(String baseOid, boolean decodeHex, int stripCnt) throws TimeoutException { return getAll(baseOid, 0, decodeHex, true, stripCnt); } /** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @param decodeHex Try to decode returned hex to ASCII * @param getNext Send GETNEXT in first packet, this will not work if you specify an exact OID * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll(boolean decodeHex, boolean getNext) throws TimeoutException { return getAll(baseOid, decodeHex, getNext); } /** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @param baseOid Override the baseOid; if null a null value is returned * @param decodeHex Try to decode returned hex to ASCII * @param getNext Send GETNEXT in first packet, this will not work if you specify an exact OID * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll(String baseOid, boolean decodeHex, boolean getNext) throws TimeoutException { return getAll(baseOid, 0, decodeHex, getNext, 0); } /** * <p> Snmpwalk the given OID and return the entire subtree. </p> * * <p> Note: the baseOid prefix will be removed from any returned * OIDs. </p> * * @param baseOid Override the baseOid; if null a null value is returned * @param getCnt The maximum number of OIDs to get; 0 or less means get as much as possible * @param decodeHex Try to decode returned hex to ASCII * @param getNext Send GETNEXT in first packet, this will not work if you specify an exact OID * @param stripCnt Strip this many elements (separated by .) from the start of OIDs * @return an ArrayList containing String arrays of two elements; OID and value * @throws TimeoutException if the hosts times out */ public ArrayList getAll(String baseOid, int getCnt, boolean decodeHex, boolean getNext, int stripCnt) throws TimeoutException { if (baseOid == null) return null; if (baseOid.charAt(0) == '.') baseOid = baseOid.substring(1, baseOid.length()); String cacheKey = host+":"+cs_ro+":"+baseOid+":"+decodeHex+":"+getNext+":"+stripCnt; if (cache.containsKey(cacheKey)) { return new ArrayList((Collection)cache.get(cacheKey)); } ArrayList l = getAllJavaSnmp(baseOid, getCnt, decodeHex, getNext, stripCnt); cache.put(cacheKey, l); return l; } private ArrayList getAllJavaSnmp(String baseOid, int getCnt, boolean decodeHex, boolean getNext, int stripCnt) throws TimeoutException { ArrayList l = new ArrayList(); try { checkSnmpContext(); // Should we get the entire subtree? boolean getAll = getCnt == 0; SNMPVarBindList var = null; boolean timeout = 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 (SocketException exp) { timeout = 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; } catch (IOException exp) { if (exp.getMessage() != null && exp.getMessage().indexOf("Receive timed out") >= 0) { timeout = true; } else { throw exp; } } if (timeout) { timeoutCnt++; if (timeoutCnt >= timeoutLimit) { throw new TimeoutException("Too many timeouts, giving up"); } else { // Re-try operation return getAllJavaSnmp(baseOid, getCnt, decodeHex, getNext, stripCnt); } } 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[] s = { oid.length() == baseOid.length() ? "" : oid.substring(baseOid.length()+1, oid.length()), data.trim() }; 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"); setSocketTimeout(500); setTimeoutLimit(1); setSnmpVersion(2); int snmpVersion = 1; try { getNext("1", 1, false, true); snmpVersion = 2; } catch (Exception e) { setSnmpVersion(1); } finally { onlyAskModule(null); setDefaultTimeoutLimit(); } 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); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -