summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorshizhendong <[email protected]>2020-04-28 19:03:57 +0800
committershizhendong <[email protected]>2020-04-28 19:03:57 +0800
commitb041c34f5bae7f217f561f0205f7cd16fa95c9ab (patch)
treef858abb17cebf4d5d49658d350ab12c5db63280c
parent6f7faa5fc4fd529e0e6a4ec8d5329b7de5221741 (diff)
fix: 修改traffic接口返回数据格式
-rw-r--r--src/main/java/com/nis/controller/TrafficController.java9
-rw-r--r--src/main/java/com/nis/dao/SnmpMibDao.java15
-rw-r--r--src/main/java/com/nis/entity/MmMib.java65
-rw-r--r--src/main/java/com/nis/service/TrafficService.java5
-rw-r--r--src/main/java/com/nis/service/impl/TrafficServiceImpl.java268
-rw-r--r--src/main/java/com/nis/util/Constant.java9
-rw-r--r--src/main/java/com/nis/util/SnmpUtil.java152
-rw-r--r--src/main/resources/mapper/SnmpMibDao.xml14
8 files changed, 447 insertions, 90 deletions
diff --git a/src/main/java/com/nis/controller/TrafficController.java b/src/main/java/com/nis/controller/TrafficController.java
index 8a56600..73c498f 100644
--- a/src/main/java/com/nis/controller/TrafficController.java
+++ b/src/main/java/com/nis/controller/TrafficController.java
@@ -1,14 +1,11 @@
package com.nis.controller;
-import com.alibaba.fastjson.JSON;
import com.nis.service.TrafficService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
-import java.util.List;
-
/**
* @author :xzyuan
* @date :Created in 2020/4/23 11:16
@@ -23,8 +20,8 @@ public class TrafficController {
private TrafficService trafficService;
@GetMapping("/traffic")
- private Object traffic(Integer dcId){
- String result = trafficService.getTrafficByIdcId(dcId);
- return result;
+ private String traffic(Integer dcId) {
+ String trafficByIdcId = trafficService.getTrafficByIdcId(dcId);
+ return trafficByIdcId;
}
}
diff --git a/src/main/java/com/nis/dao/SnmpMibDao.java b/src/main/java/com/nis/dao/SnmpMibDao.java
new file mode 100644
index 0000000..a8d47ed
--- /dev/null
+++ b/src/main/java/com/nis/dao/SnmpMibDao.java
@@ -0,0 +1,15 @@
+package com.nis.dao;
+
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * @author :shizhendong
+ * @date :Created in 2020/4/28 11:24
+ * @description:
+ * @version:
+ */
+@Mapper
+public interface SnmpMibDao {
+
+ String getSnmpIfMibTree();
+}
diff --git a/src/main/java/com/nis/entity/MmMib.java b/src/main/java/com/nis/entity/MmMib.java
new file mode 100644
index 0000000..43811fe
--- /dev/null
+++ b/src/main/java/com/nis/entity/MmMib.java
@@ -0,0 +1,65 @@
+package com.nis.entity;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * MmMib实体
+ */
+@Data
+public class MmMib implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * 名称
+ */
+ private String name;
+
+ /**
+ * 数据类型
+ */
+ private String type;
+
+ /**
+ * oid
+ */
+ private String objectID;
+
+ /**
+ * index 序号
+ */
+ private List index;
+
+ /**
+ *类型关键字
+ */
+ private String syntax;
+
+ /**
+ *访问方式(权限)
+ */
+ private String access;
+
+ /**
+ * 状态
+ */
+ private String status;
+
+ /**
+ * 描述
+ */
+ private String description;
+
+ /**
+ * 父节点
+ */
+ private String pid;
+
+ /**
+ * 子集合
+ */
+ private List<MmMib> subTree;
+}
diff --git a/src/main/java/com/nis/service/TrafficService.java b/src/main/java/com/nis/service/TrafficService.java
index fd0493c..a6d45ef 100644
--- a/src/main/java/com/nis/service/TrafficService.java
+++ b/src/main/java/com/nis/service/TrafficService.java
@@ -1,8 +1,5 @@
package com.nis.service;
-import java.util.List;
-import java.util.Map;
-
/**
* @author :xzyuan
* @date :Created in 2020/4/23 11:36
@@ -10,5 +7,7 @@ import java.util.Map;
* @version:
*/
public interface TrafficService {
+
String getTrafficByIdcId(Integer idcId);
+
}
diff --git a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java
index a2bb90b..441ac0a 100644
--- a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java
+++ b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java
@@ -1,11 +1,19 @@
package com.nis.service.impl;
-import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.nis.dao.SnmpMibDao;
import com.nis.dao.TrafficDao;
+import com.nis.entity.MmMib;
import com.nis.entity.Traffic;
import com.nis.service.TrafficService;
-import com.nis.util.RuntimeUtil;
+import com.nis.util.Constant;
+import com.nis.util.SnmpUtil;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -14,6 +22,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
/**
* @author :xzyuan
@@ -26,103 +35,200 @@ import java.util.Map;
@Slf4j
public class TrafficServiceImpl implements TrafficService {
+ private static Logger logger = LoggerFactory.getLogger(TrafficServiceImpl.class);
+
@Autowired
private TrafficDao trafficDao;
+ @Autowired
+ private SnmpMibDao snmpMibDao;
+
+
@Override
public String getTrafficByIdcId(Integer idcId) {
+ // 最终返回结果
+ List<Map<String, String>> list = new ArrayList<>();
+
List<Traffic> ipList = trafficDao.selectHost(idcId);
- String r ="";
- Map<String,String[]> desc = getDesc();
- String commandPrefix = "snmpwalk -v 2c -c public ";
- for (Traffic traffic:ipList){
- String command = commandPrefix+traffic.getHost()+" ifTable";
- List<String> result = null;
+
+ // 按照ip分组 减少请求服务次数
+ Map<String, List<Traffic>> listMap = ipList.stream().collect(Collectors.groupingBy(Traffic::getHost));
+
+ // 获取注释信息
+ Map<String, String[]> desc = getDesc();
+
+ // IfMib 文件中 oid 与 name对应关系 map
+ Map<String, String> oidWithNameMap = this.getIfMibTreeNodeOidAndNameMap();
+
+ String resultOid;
+ String name, index, direction, descHelp, descType, inOutPrefix, trafficTags, tags, trafficDirection;
+ List<Map> resultData = new ArrayList<>();
+ for (Map.Entry<String, List<Traffic>> entry : listMap.entrySet()) {
try {
- result = RuntimeUtil.run(command);
+ resultData = SnmpUtil.snmpWalk(entry.getKey(), Constant.IFTABLE_OID);
} catch (IOException e) {
- e.printStackTrace();
+ logger.error("通过SNMP采集IfTable失败,ip ->" + entry.getKey(), e);
+ }
+
+ if (CollectionUtils.isEmpty(resultData)) {
+ logger.error("通过SNMP采集IfTable失败,ip ->" + entry.getKey() + ",请检查agent 服务是否开启,是否可达。");
+ continue;
}
- //组织每一个asset对应的数据格式
- for(String s:result){
- String [] rs = s.split("=");
- if(rs[0].trim().split("\\.")[1].equals(traffic.getIfIndex().toString())){
- String direction="tx="+"\""+1+"\"";
- if(rs[0].trim().split("\\.")[0].contains("ifIn")){
- direction = "rx="+"\""+1+"\"";
+
+ Map<String, String> tempMap;
+ // 遍历 traffic 配置信息
+ for (Traffic traffic : entry.getValue()) {
+ trafficTags = traffic.getTags();
+ trafficDirection = traffic.getDirection();
+
+ for (Map map : resultData) {
+ tempMap = new HashMap();
+ boolean directionFlag = true;
+ tags = direction = "";
+
+ resultOid = map.get("oid").toString();
+ index = resultOid;
+
+ // 从最后开始截取 目前暂定截取最后一个 .
+ resultOid = resultOid.substring(0, resultOid.lastIndexOf("."));
+
+ name = oidWithNameMap.get(resultOid);
+ if (StringUtils.isNotEmpty(name)) {
+ index = index.replaceAll(resultOid + ".", "");
+ }
+
+ if (index.equals(traffic.getIfIndex().toString())) {
+ if (name.contains("ifIndex") || (!name.contains("ifIn") && !name.contains("ifOut"))) {
+ continue;
+ }
+
+ if (trafficDirection.contains(Constant.TRAFFIC_RX)) {
+ direction += Constant.TRAFFIC_RX + "=" + "\"" + 1 + "\"";
+ directionFlag = false;
+ }
+ if (trafficDirection.contains(Constant.TRAFFIC_TX)) {
+ if (!directionFlag) {
+ direction += ",";
+ }
+ direction += Constant.TRAFFIC_TX + "=" + "\"" + 1 + "\"";
+ }
+
+ if (StringUtils.isNotEmpty(trafficTags)) {
+ tags = "tags=" + "\"" + trafficTags + "\"" + ",";
+ }
+ inOutPrefix = "{ifIndex=" + "\"" + traffic.getIfIndex() + "\"" + ","
+ + "ifDescr=" + "\"" + traffic.getIfdescr() + "\"" + ","
+ + "datacenter=" + "\"" + traffic.getDatacenter() + "\"" + ","
+ + "asset=" + "\"" + traffic.getHost() + "\"" + ","
+ + tags
+ + direction + "}"
+ + " " + map.get("value");
+
+ tempMap.put(name, inOutPrefix);
+ list.add(tempMap);
}
- String descHelp = desc.get(rs[0].trim().split("\\.")[0])[0]+"\n";
- String descType = desc.get(rs[0].trim().split("\\.")[0])[1]+"\n";
- String inOutPrefix = rs[0].trim().split("\\.")[0]+"{ifIndex="+"\""+traffic.getIfIndex()+"\""+","
- +"ifDescr="+"\""+traffic.getIfdescr()+"\""+","
- +"datacenter="+"\""+traffic.getDatacenter()+"\""+","
- +"asset="+"\""+traffic.getHost()+"\""+","
- +direction+"}";
- s = descHelp + descType + inOutPrefix+" "+rs[1].split(":")[1].trim();
- r += s+"\n";
}
}
}
+ // 按照 指标名称分组之后
+ Map<Object, List<Map<String, String>>> groupListMap = list.stream().collect(Collectors.groupingBy(map -> map.keySet().toArray()[0]));
+ String r = "";
+
+ for (Map.Entry<Object, List<Map<String, String>>> entry : groupListMap.entrySet()) {
+ name = (String) entry.getKey();
+ descHelp = desc.get(name)[0] + "\n";
+ descType = desc.get(name)[1] + "\n";
+
+ r += descHelp + descType;
+
+ for (Map<String, String> pojo : entry.getValue()) {
+ r += pojo.keySet().toArray()[0] + pojo.values().iterator().next() + "\n";
+ }
+ }
return r;
}
- private static Map getDesc(){
- Map<String,String[]> map = new HashMap<>(16);
- map.put("ifInOctets",new String[]{"# HELP ifInOctets The total number" +
- " of octets received on the interface, including framing characters",
- "# TYPE ifInOctets Counter32"});
- map.put("ifInUcastPkts",new String[]{"# HELP ifInUcastPkts The number of packets, " +
- "delivered by this sub-layer to a higher (sub-)layer, which were not addressed" +
- " to a multicast or broadcast address at this sub-layer",
- "# TYPE ifInUcastPkts Counter32"});
- map.put("ifInNUcastPkts",new String[]{"# HELP ifInNUcastPkts The number of packets, " +
- "delivered by this sub-layer to a higher (sub-)layer, which were addressed to a " +
- "multicast or broadcast address at this sub-layer","# TYPE ifInNUcastPkts Counter32"});
- map.put("ifInDiscards",new String[]{"# HELP The number of inbound packets which were chosen " +
- "to be discarded even though no errors had been detected to prevent their being " +
- "deliverable to a higher-layer protocol. One possible reason for discarding such a " +
- "packet could be to free up buffer space","# TYPE ifInDiscards Counter32"});
- map.put("ifInErrors",new String[]{"# HELP ifInErrors For packet-oriented interfaces, " +
- "the number of inbound packets that contained errors preventing them from being " +
- "deliverable to a higher-layer protocol","# TYPE ifInErrors Counter32"});
- map.put("ifInUnknownProtos",new String[]{"# HELP ifInUnknownProtos For packet-oriented " +
- "interfaces, the number of packets received via the interface which were discarded " +
- "because of an unknown or unsupported protocol","# TYPE ifInUnknownProtos Counter32"});
- map.put("ifInMulticastPkts",new String[]{"# HELP The number of packets, delivered by this sub-layer to a " +
- "higher (sub-)layer, which were addressed to a multicast " +
- "address at this sub-layer. For a MAC layer protocol, this " +
- "includes both Group and Functional addresses","# TYPE ifInMulticastPkts Counter32"});
- map.put("ifInBroadcastPkts",new String[]{"# HELP The number of packets, delivered by this sub-layer to a " +
- "higher (sub-)layer, which were addressed to a broadcast" +
- "address at this sub-layer","# TYPE ifInOctets Counter32"});
- map.put("ifOutOctets",new String[]{"# HELP ifOutOctets The total number of octets transmitted out" +
- " of the interface, including framing characters","# TYPE ifInBroadcastPkts Counter32"});
- map.put("ifOutUcastPkts",new String[]{"# HELP ifOutUcastPkts The total number of packets that" +
- " higher-level protocols requested be transmitted, and which were not addressed to a multicast or " +
- "broadcast address at this sub-layer, including those that were discarded or not sent",
- "# TYPE ifOutUcastPkts Counter32"});
- map.put("ifOutNUcastPkts",new String[]{"# HELP ifOutNUcastPkts The total number of packets that " +
- "higher-level protocols requested be transmitted, and which were addressed to a multicast or " +
- "broadcast address at this sub-layer, including those that were discarded or not sent",
- "# TYPE ifOutNUcastPkts Counter32"});
- map.put("ifOutDiscards",new String[]{"# HELP ifOutDiscards The number of outbound packets which were " +
- "chosen to be discarded even though no errors had been detected to prevent their being transmitted",
- "# TYPE ifOutDiscards Counter32"});
- map.put("ifOutErrors",new String[]{"# HELP ifOutErrors For packet-oriented interfaces, the number of outbound" +
- " packets that could not be transmitted because of errors","# TYPE ifOutErrors Counter32"});
- map.put("ifOutQLen",new String[]{"# HELP ifOutQLen The length of the output packet queue (in packets)",
- "# TYPE ifOutQLen Gauge32"});
- map.put("ifOutMulticastPkts",new String[]{"# HELP The total number of packets that higher-level protocols " +
- "requested be transmitted, and which were addressed to a" +
- "multicast address at this sub-layer, including those that " +
- "were discarded or not sent. For a MAC layer protocol, this " +
- "includes both Group and Functional addresses","# TYPE ifOutMulticastPkts Counter32"});
- map.put("ifOutBroadcastPkts",new String[]{"# HELP The total number of packets that higher-level protocols " +
- "requested be transmitted, and which were addressed to a " +
- "broadcast address at this sub-layer, including those that " +
- "were discarded or not sent","# TYPE ifOutBroadcastPkts Counter32 "});
+ /**
+ * 提示信息
+ *
+ * @return
+ */
+ private static Map getDesc() {
+ Map<String, String[]> map = new HashMap<>();
+
+ map.put("ifInOctets", new String[]{"# HELP ifInOctets The total number of octets received on the interface, including framing characters - 1.3.6.1.2.1.2.2.1.10",
+ "# TYPE ifInOctets counter"});
+
+ map.put("ifInUcastPkts", new String[]{"# HELP ifInUcastPkts The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were not addressed to a multicast or broadcast address at this sub-layer - 1.3.6.1.2.1.2.2.1.11",
+ "# TYPE ifInUcastPkts counter"});
+
+ map.put("ifInNUcastPkts", new String[]{"# HELP ifInNUcastPkts The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were addressed to a multicast or broadcast address at this sub-layer - 1.3.6.1.2.1.2.2.1.12",
+ "# TYPE ifInNUcastPkts counter"});
+
+ map.put("ifInDiscards", new String[]{"# HELP ifInDiscards The number of inbound packets which were chosen to be discarded even though no errors had been detected to prevent their being deliverable to a higher-layer protocol - 1.3.6.1.2.1.2.2.1.13",
+ "# TYPE ifInDiscards counter"});
+
+ map.put("ifInErrors", new String[]{"# HELP ifInErrors For packet-oriented interfaces, the number of inbound packets that contained errors preventing them from being deliverable to a higher-layer protocol - 1.3.6.1.2.1.2.2.1.14",
+ "# TYPE ifInErrors counter"});
+
+ map.put("ifInUnknownProtos", new String[]{"# HELP ifInUnknownProtos For packet-oriented interfaces, the number of packets received via the interface which were discarded because of an unknown or unsupported protocol - 1.3.6.1.2.1.2.2.1.15",
+ "# TYPE ifInUnknownProtos counter"});
+
+ map.put("ifOutOctets", new String[]{"# HELP ifOutOctets The total number of octets transmitted out of the interface, including framing characters - 1.3.6.1.2.1.2.2.1.16",
+ "# TYPE ifOutOctets counter"});
+
+ map.put("ifOutUcastPkts", new String[]{"# HELP ifOutUcastPkts The total number of packets that higher-level protocols requested be transmitted, and which were not addressed to a multicast or broadcast address at this sub-layer, including those that were discarded or not sent - 1.3.6.1.2.1.2.2.1.17",
+ "# TYPE ifOutUcastPkts counter"});
+
+ map.put("ifOutNUcastPkts", new String[]{"# HELP ifOutNUcastPkts The total number of packets that higher-level protocols requested be transmitted, and which were addressed to a multicast or broadcast address at this sub-layer, including those that were discarded or not sent - 1.3.6.1.2.1.2.2.1.18",
+ "# TYPE ifOutNUcastPkts counter"});
+
+ map.put("ifOutDiscards", new String[]{"# HELP ifOutDiscards The number of outbound packets which were chosen to be discarded even though no errors had been detected to prevent their being transmitted - 1.3.6.1.2.1.2.2.1.19",
+ "# TYPE ifOutDiscards counter"});
+
+ map.put("ifOutErrors", new String[]{"# HELP ifOutErrors For packet-oriented interfaces, the number of outbound packets that could not be transmitted because of errors - 1.3.6.1.2.1.2.2.1.20",
+ "# TYPE ifOutErrors counter"});
+
+ map.put("ifOutQLen", new String[]{"# HELP ifOutQLen The length of the output packet queue (in packets). - 1.3.6.1.2.1.2.2.1.21",
+ "# TYPE ifOutQLen gauge"});
return map;
}
+
+ private Map<String, String> getIfMibTreeNodeOidAndNameMap() {
+ String ifMibTree = snmpMibDao.getSnmpIfMibTree();
+
+ Map map = JSONObject.parseObject(ifMibTree, Map.class);
+ List<MmMib> mmMibs = JSONArray.parseArray(JSONArray.toJSONString(new ArrayList<JSONArray>(map.values()).get(0)), MmMib.class);
+
+ Map<String, String> oidWithNameMap = new HashMap<>();
+
+ List<MmMib> subTree;
+ Map<String, String> collectMap;
+
+ for (MmMib mmMib : mmMibs) {
+ oidWithNameMap.put(mmMib.getObjectID(), mmMib.getName());
+ // 如果存在子树 则继续
+ if (CollectionUtils.isNotEmpty(mmMib.getSubTree())) {
+ subTree = getSubTree(mmMib.getSubTree());
+ collectMap = subTree.stream().collect(Collectors.toMap(MmMib::getObjectID, MmMib::getName));
+ oidWithNameMap.putAll(collectMap);
+ }
+ }
+
+ return oidWithNameMap;
+ }
+
+ private List<MmMib> getSubTree(List<MmMib> list) {
+ List<MmMib> resultList = new ArrayList<>();
+ for (MmMib mmMib : list) {
+ resultList.add(mmMib);
+ if (CollectionUtils.isNotEmpty(mmMib.getSubTree())) {
+ List<MmMib> subTree = getSubTree(mmMib.getSubTree());
+ resultList.addAll(subTree);
+ }
+ }
+ return resultList;
+ }
}
diff --git a/src/main/java/com/nis/util/Constant.java b/src/main/java/com/nis/util/Constant.java
index d0050a6..db8abae 100644
--- a/src/main/java/com/nis/util/Constant.java
+++ b/src/main/java/com/nis/util/Constant.java
@@ -82,4 +82,13 @@ public class Constant {
}
DB_TYPE = databaseId;
}
+
+ // ifTable 对应 oid
+ public static final String IFTABLE_OID = "1.3.6.1.2.1.2.2";
+
+ // 流量入方向
+ public static final String TRAFFIC_RX = "rx";
+
+ // 流量出方向
+ public static final String TRAFFIC_TX = "tx";
}
diff --git a/src/main/java/com/nis/util/SnmpUtil.java b/src/main/java/com/nis/util/SnmpUtil.java
new file mode 100644
index 0000000..4bea2ef
--- /dev/null
+++ b/src/main/java/com/nis/util/SnmpUtil.java
@@ -0,0 +1,152 @@
+package com.nis.util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.snmp4j.*;
+import org.snmp4j.event.ResponseEvent;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.smi.*;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class SnmpUtil {
+
+ private static Logger logger = LoggerFactory.getLogger(SnmpUtil.class);
+
+ private static Snmp snmp = null;
+
+ // 默认版本 v2
+ private static final int DEFAULT_VERSION = SnmpConstants.version2c;
+ private static final String DEFAULT_PROTOCOL = "udp";
+ private static final long DEFAULT_TIMEOUT = 1000L;
+ private static final int DEFAULT_RETRY = 3;
+
+ // 默认团体名
+ private static final String DEFAULT_COMMUNITY = "public";
+
+ // 默认端口
+ private static final Integer DEFAULT_PORT = 161;
+
+ /**
+ * 获取target
+ *
+ * @param ip
+ * @return
+ */
+ public static Target getTatget(String ip) {
+ Target target = new CommunityTarget();
+ // 默认版本 v2
+ target.setVersion(DEFAULT_VERSION);
+ // 团体名
+ ((CommunityTarget) target).setCommunity(new OctetString(DEFAULT_COMMUNITY));
+ // 超时时间
+ target.setTimeout(DEFAULT_TIMEOUT);
+ // 重试次数
+ target.setRetries(DEFAULT_RETRY);
+
+ Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip + "/" + DEFAULT_PORT);
+ target.setAddress(address);
+
+ return target;
+ }
+
+
+ /**
+ * snmpwalk
+ *
+ * @param ip
+ * @param oid
+ * @return
+ * @throws IOException
+ */
+ public static List<Map> snmpWalk(String ip, String oid) throws IOException {
+ List<Map> resultData = new ArrayList<>();
+ try {
+ TransportMapping transport = new DefaultUdpTransportMapping();
+ snmp = new Snmp(transport);
+
+ Target target = getTatget(ip);
+ snmp.listen();
+
+ PDU pdu = new PDU();
+
+ OID targetOID = new OID(oid);
+ pdu.add(new VariableBinding(targetOID));
+
+ // 结束标识
+ boolean finished = false;
+
+ Map map;
+ while (!finished) {
+ VariableBinding vb = null;
+ ResponseEvent respEvent = snmp.getNext(pdu, target);
+
+ PDU response = respEvent.getResponse();
+
+ // 为空则直接结束
+ if (response == null) {
+ finished = true;
+ break;
+ } else {
+ vb = response.get(0);
+ }
+
+ // 判断是否结束
+ finished = checkWalkFinished(targetOID, pdu, vb);
+ if (!finished) {
+ pdu.setRequestID(new Integer32(0));
+ pdu.set(0, vb);
+
+ map = new HashMap();
+ map.put("oid", vb.getOid().toString());
+ map.put("value", vb.getVariable().toString());
+ map.put("type", vb.getVariable().getSyntaxString());
+ resultData.add(map);
+ } else {
+ // 获取结束
+ snmp.close();
+ }
+ }
+ } finally {
+ if (snmp != null) {
+ try {
+ snmp.close();
+ } catch (Exception e) {
+ logger.error("关闭snmp失败", e);
+ }
+ }
+ }
+ return resultData;
+ }
+
+ /**
+ * 判断walk结束标识
+ *
+ * @param targetOID
+ * @param pdu
+ * @param vb
+ * @return
+ */
+ private static boolean checkWalkFinished(OID targetOID, PDU pdu, VariableBinding vb) {
+ boolean finished = false;
+ if (pdu.getErrorStatus() != 0) {
+ finished = true;
+ } else if (vb.getOid() == null) {
+ finished = true;
+ } else if (vb.getOid().size() < targetOID.size()) {
+ finished = true;
+ } else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
+ finished = true;
+ } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
+ finished = true;
+ } else if (vb.getOid().compareTo(targetOID) <= 0) {
+ finished = true;
+ }
+ return finished;
+ }
+}
diff --git a/src/main/resources/mapper/SnmpMibDao.xml b/src/main/resources/mapper/SnmpMibDao.xml
new file mode 100644
index 0000000..1f1bfbe
--- /dev/null
+++ b/src/main/resources/mapper/SnmpMibDao.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.nis.dao.SnmpMibDao">
+
+ <select id="getSnmpIfMibTree" resultType="java.lang.String">
+ SELECT
+ tree
+ FROM
+ snmp_mib
+ WHERE
+ name = 'IF-MIB'
+ </select>
+
+</mapper>