/** * 向管理进程发送Trap报文 * * @throws IOException */ public void sendPDU() throws IOException { // 设置 target CommunityTarget target = new CommunityTarget(); target.setAddress(targetAddress); // 通信不成功时的重试次数 target.setRetries(2); // 超时时间 target.setTimeout(1500); // snmp版本 target.setVersion(SnmpConstants.version2c); // 创建 PDU PDU pdu = new PDU(); pdu.add( new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"), new OctetString("SnmpTrap"))); pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.2"), new OctetString("JavaEE"))); pdu.add( new VariableBinding( new OID(".1.3.6.1.4.1.12612.220.11.1.3.0.1"), new OctetString("test_barco"))); pdu.setType(PDU.TRAP); // 向Agent发送PDU,并接收Response ResponseEvent respEvnt = snmp.send(pdu, target); // 解析Response if (respEvnt != null && respEvnt.getResponse() != null) { Vector<VariableBinding> recVBs = respEvnt.getResponse().getVariableBindings(); for (int i = 0; i < recVBs.size(); i++) { VariableBinding recVB = recVBs.elementAt(i); System.out.println(recVB.getOid() + " : " + recVB.getVariable()); } } }
private PDU CreateAndSetPdu() { PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(oidFromInput))); pdu.setType(PDU.GET); pdu.setRequestID(new Integer32(2)); return pdu; }
private ResponseEvent snmpGet(String targetOid) throws IOException { PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(targetOid))); pdu.setType(PDU.GET); // send the PDU return snmp.send(pdu, target); }
private void notifyResponse(ResponseEvent response, String targetOid) { if (response == null) { for (ResponseHandler responseHandler : responseHandlers) { responseHandler.onTimeout(targetOid); } } else { PDU responsePDU = response.getResponse(); int errorStatus = responsePDU.getErrorStatus(); int errorIndex = responsePDU.getErrorIndex(); String errorStatusText = responsePDU.getErrorStatusText(); switch (errorStatus) { case SnmpConstants.SNMP_ERROR_SUCCESS: for (ResponseHandler responseHandler : responseHandlers) { responseHandler.onSuccess(targetOid); } break; default: if (log.isDebugEnabled()) { log.debug("Error: Request Failed"); log.debug("Error Status = " + errorStatus); log.debug("Error Index = " + errorIndex); log.debug("Error Status Text = " + errorStatusText); } for (ResponseHandler responseHandler : responseHandlers) { responseHandler.onError(targetOid, errorStatus, errorStatusText); } break; } } }
/** * This method creates the requst and puts it in an PDU object. This object will be returnd and * used from Methods such as get,walk and getnext. * * @param type - the type of the response, possible are PDU.GET,PDU.GETNEXT, PDU.GETBULK * @param oids - the requested OIDs * @return - the request PDU * @see org.snmp4j.ScopedPDU */ public PDU createPDU(int type, OID[] oids) { // create the PDU PDU requestPDU = new ScopedPDU(); requestPDU.setType(type); // put the oid you want to get for (OID oid : oids) { requestPDU.add(new VariableBinding(oid)); } return requestPDU; }
public void testTrap() throws Exception { File alarmsFile = new File("alarms.txt"); alarmsFile.delete(); PDU trap = new PDU(); trap.setType(PDU.TRAP); OID oid = new OID("1.2.3.4.5"); trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, oid)); trap.add( new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(5000))); // put your uptime here trap.add(new VariableBinding(SnmpConstants.sysDescr, new OctetString("System Description"))); Variable alarmCode = new OctetString("777"); Variable agentId = new OctetString("AGENT_ID"); Variable alarmText = new OctetString("ALARM"); Variable agentAddress = new OctetString("127.0.0.1/161"); trap.add(new VariableBinding(new OID("1.2.3.4.5.1"), alarmCode)); trap.add(new VariableBinding(new OID("1.2.3.4.5.2"), agentId)); trap.add(new VariableBinding(new OID("1.2.3.4.5.3"), alarmText)); trap.add(new VariableBinding(new OID("1.2.3.4.5.4"), agentAddress)); server.readAndSaveTrap(trap); assertTrue(alarmsFile.exists()); String fileContent = SnmpNmsTest.readFileAsString("alarms.txt"); assertTrue(fileContent.indexOf("AGENT_ID") > -1); assertTrue(fileContent.indexOf("777") > -1); assertTrue(fileContent.indexOf("ALARM") > -1); }
/** * This method is capable of handling multiple OIDs * * @param oids * @return * @throws IOException */ public ResponseEvent get(OID... oids) throws IOException { PDU pdu = new PDU(); for (OID oid : oids) { pdu.add(new VariableBinding(oid)); } pdu.setType(PDU.GET); ResponseEvent event = snmp.send(pdu, getTarget(), null); if (event != null) { return event; } throw new RuntimeException("GET timed out"); }
public void updateByValue( URI url, List<Variable> values, SnmpUriCallback callback, Object userObject) throws UnknownHostException { Request request = createSnmpRequest(url); PDU pdu = request.getPdu(); pdu.setType(PDU.SET); OID[] oids = request.getOIDs(); for (int i = 0; i < oids.length && i < values.size(); i++) { pdu.add(new VariableBinding(oids[i], values.get(i))); } sendSnmpRequest(request, pdu, url, callback, userObject); }
private void requestAndVerifyResponse(int pduType, int version) throws Exception { PDU pdu = createPDU(version); for (AnticipatedRequest a : m_requestedVarbinds) { pdu.add(a.getRequestVarbind()); } pdu.setType(pduType); PDU response = sendRequest(pdu, version); assertNotNull("request timed out", response); System.err.println("Response is: " + response); assertTrue( "unexpected report pdu: " + ((VariableBinding) response.getVariableBindings().get(0)).getOid(), response.getType() != PDU.REPORT); assertEquals( "Unexpected number of varbinds returned.", m_requestedVarbinds.size(), response.getVariableBindings().size()); for (int i = 0; i < m_requestedVarbinds.size(); i++) { AnticipatedRequest a = m_requestedVarbinds.get(i); VariableBinding vb = response.get(i); a.verify(vb); } reset(); }
public void sendByBinding( URI url, List<VariableBinding> values, int pduType, SnmpUriCallback callback, Object userObject) throws UnknownHostException { Request request = createSnmpRequest(url); PDU pdu = request.getPdu(); pdu.setType(pduType); for (VariableBinding vb : values) { pdu.add(vb); } sendSnmpRequest(request, pdu, url, callback, userObject); }
/** * This method returns true or false, which depend on the response PDU. If the response PDU is not * null and don't have an error, true will be returned. * * @param responsePDU the responsePDU, which will be checked for errors. * @return - true if no error was invoked else false. * @throws PDURequestFailedException - If an error occurred in the response PDU. * @throws SNMPTimeOutException - If a timeout occured * @see org.snmp4j.PDU */ public boolean checkResponsePDU(PDU responsePDU) throws PDURequestFailedException, SNMPTimeOutException { if (responsePDU != null) if (responsePDU.getErrorStatus() == PDU.noError) return true; else throw new PDURequestFailedException(responsePDU); else throw new SNMPTimeOutException("Timeout: No Response from " + authentication.getAddress()); }
private PDU createPDU(SnmpTrapInfo snmpTrapInfo) { PDU trap = new PDU(); trap.setType(PDU.TRAP); int alertType = snmpTrapInfo.getAlertType() + 1; if (alertType > 0) { trap.add( new VariableBinding(SnmpConstants.sysUpTime, new OctetString(new Date().toString()))); trap.add( new VariableBinding( SnmpConstants.snmpTrapOID, getOID(CsSnmpConstants.TRAPS_PREFIX + alertType))); trap.add( new VariableBinding( getOID(CsSnmpConstants.DATA_CENTER_ID), new UnsignedInteger32(snmpTrapInfo.getDataCenterId()))); trap.add( new VariableBinding( getOID(CsSnmpConstants.POD_ID), new UnsignedInteger32(snmpTrapInfo.getPodId()))); trap.add( new VariableBinding( getOID(CsSnmpConstants.CLUSTER_ID), new UnsignedInteger32(snmpTrapInfo.getClusterId()))); if (snmpTrapInfo.getMessage() != null) { trap.add( new VariableBinding( getOID(CsSnmpConstants.MESSAGE), new OctetString(snmpTrapInfo.getMessage()))); } else { throw new CloudRuntimeException(" What is the use of alert without message "); } if (snmpTrapInfo.getGenerationTime() != null) { trap.add( new VariableBinding( getOID(CsSnmpConstants.GENERATION_TIME), new OctetString(snmpTrapInfo.getGenerationTime().toString()))); } else { trap.add(new VariableBinding(getOID(CsSnmpConstants.GENERATION_TIME))); } } else { throw new CloudRuntimeException(" Invalid alert Type "); } return trap; }
public void snmpWalk(String oidFrom) throws SnmpException { PDU request = new PDU(); request.setType(PDU.GETNEXT); request.add(new VariableBinding(new OID(oidFrom))); request.setNonRepeaters(0); OID rootOID = request.get(0).getOid(); PDU response = null; int objects = 0; int requests = 0; long startTime = System.currentTimeMillis(); try { Snmp snmp = new Snmp(new DefaultUdpTransportMapping()); snmp.listen(); m_sessionDestroyed = false; do { requests++; ResponseEvent responseEvent = snmp.send(request, getTarget(getReadCommunity())); response = responseEvent.getResponse(); if (response != null) { objects += response.size(); } } while (!processWalk(response, request, rootOID) && !m_sessionDestroyed); } catch (SnmpException e) { throw e; } catch (Exception e) { e.printStackTrace(); throw new SnmpException(e.getMessage()); } if (m_snmpResponseHandler != null) { m_snmpResponseHandler.requestStats(requests, objects, System.currentTimeMillis() - startTime); } }
public String snmpGet(String strAddress, String community, String strOID) // SNMPget { String str = ""; try { OctetString community1 = new OctetString(community); strAddress = strAddress + "/" + 161; // Direccion + Puerto SNMP Address targetaddress = new UdpAddress(strAddress); // direccion con puerto TransportMapping transport = new DefaultUdpTransportMapping(); transport.listen(); /* * Este metodo regresa un Target, que contiene informacion acerca de los * datos y como deben ser mostrados y sus rangos. */ CommunityTarget comtarget = new CommunityTarget(); comtarget.setCommunity(community1); comtarget.setVersion(SnmpConstants.version1); comtarget.setAddress(targetaddress); comtarget.setRetries(2); comtarget.setTimeout(5000); PDU pdu = new PDU(); ResponseEvent response; Snmp snmp; pdu.add(new VariableBinding(new OID(strOID))); pdu.setType(PDU.GET); snmp = new Snmp(transport); response = snmp.get(pdu, comtarget); if (response != null) { if (response.getResponse().getErrorStatusText().equalsIgnoreCase("Success")) { PDU pduresponse = response.getResponse(); str = pduresponse.getVariableBindings().firstElement().toString(); if (str.contains("=")) { int len = str.indexOf("="); str = str.substring(len + 1, str.length()); } } } else { System.out.println("Feeling like a TimeOut occured "); } // En caso de que ocurra un Time out snmp.close(); // cierra conexión } catch (Exception e) { } System.out.println("Response= " + str); // en caso de ocurrio error lo arroja return str; }
@Override public void onResponse(ResponseEvent event) { SnmpUriResponse response = new SnmpUriResponse(SnmpUriResponse.Type.TIMEOUT); PDU responsePDU = event.getResponse(); if (responsePDU != null) { if (responsePDU.getErrorStatus() != PDU.noError) { response = new SnmpUriResponse(responsePDU.getErrorStatus()); } else { response = new SnmpUriResponse( Collections.singletonList( responsePDU .getVariableBindings() .toArray(new VariableBinding[responsePDU.size()]))); } } callback.onResponse(response, url, event.getUserObject()); }
public void SentGetSnmp() throws IOException { TransportMapping transport = new DefaultUdpTransportMapping(); transport.listen(); // Target CommunityTarget target = CreateAndSetTarget(); // PDU PDU pdu = CreateAndSetPdu(); // SNMP Snmp snmp = new Snmp(transport); // System.out.println("Sending request to " + ipFromInput + " ..."); ResponseEvent response = snmp.get(pdu, target); if (response != null) { // System.out.println("Got response from " + ipFromInput); PDU responsePdu = response.getResponse(); if (responsePdu != null) { int errorStatus = responsePdu.getErrorStatus(); int errorIndex = responsePdu.getErrorIndex(); String errorStatusText = responsePdu.getErrorStatusText(); if (errorStatus == PDU.noError) { readResponse(responsePdu.getVariableBindings()); // System.out.println(responsePdu.getVariableBindings().getClass()); // System.out.println("SNMP get response: " + responsePdu.getVariableBindings()); } else { System.out.println("Error: Request Failed"); System.out.println("Error Status: " + errorStatus); System.out.println("Error Index: " + errorIndex); System.out.println("Error Status Text: " + errorStatusText); } } else { System.out.println("Error: PDU response is null"); } } else { System.out.println("Error: Agent Timeout"); } snmp.close(); }
/** * Method which takes a single OID and returns the response from the agent as a String. * * @param oid * @return * @throws IOException */ public String getAsString(OID... oid) throws IOException { // ResponseEvent event = get(new OID[]{oid}); // return event.getResponse().get(0).getVariable().toString(); ResponseEvent event = get(oid); PDU response = event.getResponse(); int size = oid.length; // VariableBinding variableBinding=response.get(0); // Variable variable=variableBinding.getVariable(); // String varStirng=variable.toString(); // return varStirng; StringBuilder builder = new StringBuilder(); for (int i = 0; i < size; i++) { VariableBinding variableBinding = response.get(i); Variable variable = variableBinding.getVariable(); String varStirng = variable.toString(); String oi = variableBinding.getOid().toString(); builder.append("oid: ").append(oi).append(" var: ").append(varStirng).append("\n"); } return builder.toString(); }
void snmpSetValue(String oid, int syntax, String value) throws SnmpException { VariableBinding varbind = getVarBindForSetRequest(oid, syntax, value); PDU request = new PDU(); request.setType(PDU.SET); request.add(varbind); PDU response = null; long startTime = System.currentTimeMillis(); try { Snmp snmp = new Snmp(new DefaultUdpTransportMapping()); snmp.listen(); ResponseEvent responseEvent = snmp.send(request, getTarget(getWriteCommunity())); response = responseEvent.getResponse(); // System.out.println(response); } catch (Exception e) { e.printStackTrace(); throw new SnmpException(e.getMessage()); } }
/** * The method get can be specified with an Array of requested OIDs. A Vector with elements of the * subclass VariableBinding will be returned. OID requested from the method GET can only return a * value. Therefore the OIDd must be a scalar and not a branch. * * @param oids - the requested OIDs * @return - a Vector with VariableBindings * @throws SNMPTimeOutException - will be thrown if a timeout with request happens * @throws PDURequestFailedException - will be thrown if an error occurs within the request * @see org.snmp4j.smi.VariableBinding */ public Vector<? extends VariableBinding> get(OID[] oids) throws SNMPTimeOutException, PDURequestFailedException { ResponseEvent responseEvent = null; Vector<? extends VariableBinding> vbs = null; try { // send the PDU responseEvent = snmp.send(createPDU(PDU.GET, oids), authentication.getTarget()); Logger.getLogger(SnmpManager.class.getName()).log(Level.INFO, responseEvent.toString()); } catch (IOException e) { System.err.println(e.getMessage()); } // extract the response PDU (could be null if timed out) if (responseEvent != null) { PDU responsePDU = responseEvent.getResponse(); if (checkResponsePDU(responsePDU)) vbs = responsePDU.getVariableBindings(); } else { throw new SNMPTimeOutException(); } return vbs; }
private boolean processWalk(PDU response, PDU request, OID rootOID) throws SnmpException { if ((response == null) || (response.getErrorStatus() != 0) || (response.getType() == PDU.REPORT)) { return true; } boolean finished = false; OID lastOID = request.get(0).getOid(); for (int i = 0; (!finished) && (i < response.size()); i++) { VariableBinding vb = response.get(i); if ((vb.getOid() == null) || (vb.getOid().size() < rootOID.size()) || (rootOID.leftMostCompare(rootOID.size(), vb.getOid()) != 0)) { finished = true; } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) { outputResponse(vb); finished = true; } else if (vb.getOid().compareTo(lastOID) <= 0) { throw new SnmpException( "Variable received is not lexicographic successor of requested one:" + vb.toString() + " <= " + lastOID); } else { outputResponse(vb); lastOID = vb.getOid(); } } if (response.size() == 0) { finished = true; } if (!finished) { VariableBinding next = response.get(response.size() - 1); next.setVariable(new Null()); request.set(0, next); request.setRequestID(new Integer32(0)); } return finished; }
public void browse(URI url, SnmpUriCallback callback, Object userObject) throws UnknownHostException { Request request = createSnmpRequest(url); PDU pdu = request.getPdu(); switch (request.getType()) { case GET: pdu.setType(PDU.GET); pdu.addAll(VariableBinding.createFromOIDs(request.getOIDs())); sendSnmpRequest(request, pdu, url, callback, userObject); break; case NEXT: pdu.setType(PDU.GETNEXT); pdu.addAll(VariableBinding.createFromOIDs(request.getOIDs())); sendSnmpRequest(request, pdu, url, callback, userObject); break; case SUBTREE: TreeUtils treeUtils = new TreeUtils(snmp, pduFactory); TreeListener treeListener = new AsyncTreeListener(url, callback); treeUtils.walk(request.getTarget(), request.getOIDs(), userObject, treeListener); break; } }
/** * This method returns a Target, which contains information about where the data should be fetched * and how. * * @return * @throws IOException */ private Target getTarget() throws IOException { Address targetAddress = GenericAddress.parse(address); // System.out.println(targetAddress.isValid()); // CommunityTarget target = new CommunityTarget(); // target.setCommunity(new OctetString("public")); // target.setAddress(targetAddress); // System.out.println(target.getAddress()); // target.setRetries(2); // target.setTimeout(5500); // target.setVersion(SnmpConstants.version2c); // System.out.println(target.toString()); // return target; CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString(COMMUNITYKEY)); target.setAddress(targetAddress); target.setRetries(2); target.setTimeout(100); target.setVersion(SnmpConstants.version1); // creating PDU PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 1}))); pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 2}))); pdu.setType(PDU.GETNEXT); // sending request ResponseListener listener = new ResponseListener() { public void onResponse(ResponseEvent event) { // Always cancel async request when response has been received // otherwise a memory leak is created! Not canceling a request // immediately can be useful when sending a request to a broadcast // address. ((Snmp) event.getSource()).cancel(event.getRequest(), this); // System.out.println("Received response PDU is: "+event.getResponse()); } }; snmp.send(pdu, target, null, listener); return target; }
/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { TransportMapping transport = new DefaultUdpTransportMapping(); Snmp snmp = new Snmp(transport); MessageDispatcherImpl dispatcher = new MessageDispatcherImpl(); transport.listen(); Address targetAddress = new UdpAddress("202.144.0.178/161"); // setting up target CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString("public")); target.setAddress(targetAddress); target.setRetries(2); target.setTimeout(1500); target.setVersion(SnmpConstants.version1); // creating PDU PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 1}))); pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 2}))); pdu.setType(PDU.GETNEXT); // sending request ResponseListener listener = new ResponseListener() { public void onResponse(ResponseEvent event) { // Always cancel async request when response has been received // otherwise a memory leak is created! Not canceling a request // immediately can be useful when sending a request to a // broadcast // address. ((Snmp) event.getSource()).cancel(event.getRequest(), this); System.out.println("Received response PDU is: " + event.getResponse()); } }; snmp.set(pdu, target, null, listener); // snmp.sendPDU(pdu, target, null, listener); }
public static List<String> get( Snmp snmp, String address, String community, int version, int retry, String[] oids) { List<String> list = new ArrayList<String>(); Address targetAddress = GenericAddress.parse(address); CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString(community)); target.setAddress(targetAddress); target.setVersion(version); target.setTimeout(1000); target.setRetries(retry); PDU pdu = new PDU(); pdu.setType(PDU.GET); for (String oid : oids) { pdu.add(new VariableBinding(new OID(oid))); } try { ResponseEvent response = snmp.send(pdu, target); PDU resposePdu = response.getResponse(); if (resposePdu != null) { Vector<?> v = resposePdu.getVariableBindings(); for (Object o : v) { if (o instanceof VariableBinding) { VariableBinding vb = (VariableBinding) o; String r = vb.getVariable().toString(); list.add(r); } } } } catch (IOException e) { e.printStackTrace(); } return list; }
public void testMakeGet() throws Exception { assertTrue(true); File queriesFile = new File("queries.txt"); queriesFile.delete(); PDU response = new PDU(); OID oid = new OID(".1.3.6.1.2.1.1.1.0"); Variable systemDescription = new OctetString("System"); VariableBinding binding = new VariableBinding(oid, systemDescription); Vector<VariableBinding> variableBindings = new Vector<VariableBinding>(); variableBindings.add(binding); response.setVariableBindings(variableBindings); server.readAndSaveGetResult(response, "AGENT_ID"); assertTrue(queriesFile.exists()); String fileContent = SnmpNmsTest.readFileAsString("queries.txt"); assertTrue(fileContent.indexOf("AGENT_ID") > -1); assertTrue(fileContent.indexOf("System") > -1); }
public void snmpSet(String strAddress, String community, String strOID, int Value) { strAddress = strAddress + "/" + 161; // Direccion + Puerto SNMP Address targetAddress = GenericAddress.parse(strAddress); // direccion con puerto Snmp snmp; try { TransportMapping transport = new DefaultUdpTransportMapping(); snmp = new Snmp(transport); transport.listen(); /* * Este metodo regresa un Target, que contiene informacion acerca de los * datos y como deben ser mostrados y sus rangos. */ CommunityTarget target = new CommunityTarget(); // representa las propiedades del target SNMP basado en proceso de // modelos target.setCommunity(new OctetString(community)); target.setAddress(targetAddress); target.setRetries(2); target.setTimeout(5000); target.setVersion(SnmpConstants.version1); PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(strOID), new Integer32(Value))); pdu.setType(PDU.SET); ResponseListener listener = new ResponseListener() { @Override // public method declared in Object public void onResponse(ResponseEvent event) { ((Snmp) event.getSource()).cancel(event.getRequest(), this); System.out.println("Set Status is:" + event.getResponse().getErrorStatusText()); // Impresion del status de la respuesta } }; snmp.send(pdu, target, null, listener); // envio de parametros snmp.close(); // cierra socket snmp } catch (Exception e) { } }
/** * Read a variable saved into @DriverConfiguration object * * @param propertyConfiguration driver configuration object * @throws GenericException if configuration fatal error */ @Override public void readValue(DriverConfiguration propertyConfiguration) throws GenericException { try { ResponseEvent response = snmpGet(String.valueOf(propertyConfiguration.getValue())); if (response != null) { if (log.isDebugEnabled()) { log.debug("Got Snmp Get Response from Agent"); } PDU responsePDU = response.getResponse(); if (responsePDU != null) { int errorStatus = responsePDU.getErrorStatus(); if (errorStatus == PDU.noError) { Vector<? extends VariableBinding> variableBindings = responsePDU.getVariableBindings(); if (log.isDebugEnabled()) { log.debug(String.format("Snmp Get Response = %s", variableBindings)); } VariableBinding variableBinding = variableBindings.get(0); Variable variable = variableBinding.getVariable(); Object value = convert(variable, getValueType(variable)); setValue(propertyConfiguration, value); } else { notifyResponse(response, propertyConfiguration.getName()); } } else { if (log.isDebugEnabled()) { log.debug("Error: Response PDU is null"); } } } else { notifyResponse(response, propertyConfiguration.getName()); } } catch (Exception e) { throw new GenericException(e); } }
private static Vector<VariableBinding> getTableRow( Snmp snmp, CommunityTarget target, String[] colOids, String firstOid) { PDU pdu = new PDU(); pdu.setType(PDU.GETNEXT); for (String oid : colOids) { pdu.add(new VariableBinding(new OID(oid))); } Vector<VariableBinding> v = null; try { ResponseEvent response = snmp.send(pdu, target); PDU resposePdu = response.getResponse(); if (resposePdu != null) { v = resposePdu.getVariableBindings(); if (v != null && v.size() > 0) { VariableBinding vb = v.get(0); String oid = vb.getOid().toString(); if (!oid.startsWith(firstOid)) return null; } } } catch (IOException e) { e.printStackTrace(); } return v; }
public static List<String[]> getTable( Snmp snmp, String address, String community, int version, int retry, String[] colOids) { List<String[]> list = new ArrayList<String[]>(); Address targetAddress = GenericAddress.parse(address); CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString(community)); target.setAddress(targetAddress); target.setVersion(version); target.setTimeout(1000); target.setRetries(retry); PDU pdu = new PDU(); pdu.setType(PDU.GETNEXT); for (String oid : colOids) { pdu.add(new VariableBinding(new OID(oid))); } int i = 0; String firstOid = colOids[0]; Vector<VariableBinding> row = null; do { row = getTableRow(snmp, target, colOids, firstOid); if (row != null && colOids.length == row.size()) { String[] ss = new String[colOids.length]; for (int n = 0; n < colOids.length; n++) { VariableBinding vb = row.get(n); String r = vb.getVariable().toString(); colOids[n] = vb.getOid().toString(); ss[n] = r; } list.add(ss); } } while (i++ < 200 && row != null); return list; }
/** * @param ip * @param community */ public static void snmpGetList(String ip, String community, List<String> oidList) { CommunityTarget target = SnmpUtil.createDefault(ip, community); Snmp snmp = null; try { PDU pdu = new PDU(); for (String oid : oidList) { pdu.add(new VariableBinding(new OID(oid))); } DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping(); transport.listen(); snmp = new Snmp(transport); System.out.println("------->发送消息<-------"); pdu.setType(PDU.GET); ResponseEvent respEvent = snmp.send(pdu, target); System.out.println("PeerAddress:" + respEvent.getPeerAddress()); PDU response = respEvent.getResponse(); if (response == null) { System.out.println("response is null, request time out"); } else { System.out.println("response pdu size is " + response.size()); for (int i = 0; i < response.size(); i++) { VariableBinding vb = response.get(i); System.out.println(vb.getOid() + " = " + vb.getVariable()); } } System.out.println("SNMP GET List OID value finished !"); } catch (Exception e) { e.printStackTrace(); System.out.println("SNMP GetList Exception:" + e); } finally { if (snmp != null) { try { snmp.close(); } catch (IOException ex1) { snmp = null; } } } }