kongdeqiang
2022-12-16 daf6a95086087ec99232eea8b4648b7541881f7c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package com.wgcloud.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.security.SecurityModel;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
 
import java.io.IOException;
import java.util.*;
 
public class SnmpTestUtil {
    private static final Logger logger = LoggerFactory.getLogger(SnmpTestUtil.class);
    private static Snmp snmp   = null;
    private CommunityTarget target;
 
    //传入要查询的主机ip
    private String hostIp;
    //传入要查询的端口号
    private String hostPort;
    //传入要查询的团体名
    private String community ;
    //接收要查询的oids
    private String oid;
 
    public String getHostIp() {
        return hostIp;
    }
 
    public void setHostIp(String hostIp) {
        this.hostIp = hostIp;
    }
 
    public String getHostPort() {
        return hostPort;
    }
 
    public void setHostPort(String hostPort) {
        this.hostPort = hostPort;
    }
 
    public String getCommunity() {
        return community;
    }
 
    public void setCommunity(String community) {
        this.community = community;
    }
 
    private String addressGet ;
 
    //获取设备描述信息
    private String healthOID1 = "1.3.6.1.4.1";
    //设备电源状态
    String healthOID2 = "1.3.6.1.";
    //获取系统温度
    private String healthOID3 = "1.3.6.";
 
    public  SnmpTestUtil(String hostIp, String hostPort, String snmpCommunity, String oid){
        this.setHostIp(hostIp);
        this.setHostPort(hostPort);
        this.setCommunity(snmpCommunity);
        this.oid = oid;
    }
 
    public void  initSnmp() throws IOException {
        snmp = new Snmp(new DefaultUdpTransportMapping());
        //开启监听
        snmp.listen();
    }
 
    private Target createTarget(String oid) {
        //先得到连接的ip和端口号
        this.addressGet = "udp:" + this.getHostIp()+"/"+this.getHostPort();
 
        Target target = null;
        int version = 1;
        if (!(version == SnmpConstants.version3 || version == SnmpConstants.version2c || version == SnmpConstants.version1)) {
            //log.error("参数version异常");
            return target;
        }
//        if (version == SnmpConstants.version3) {
//            target = new UserTarget();
//            //snmpV3需要设置安全级别和安全名称,其中安全名称是创建snmp指定user设置的new OctetString("SNMPV3")
//            target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
//            target.setSecurityName(new OctetString(this.username));
//        } else
        {
            //snmpV1和snmpV2需要指定团体名名称
            target = new CommunityTarget();
            ((CommunityTarget) target).setCommunity(new OctetString(this.community));
            if (version == SnmpConstants.version2c) {
                target.setSecurityModel(SecurityModel.SECURITY_MODEL_SNMPv2c);
            }
        }
        target.setVersion(version);
        //必须指定,没有设置就会报错。
        target.setAddress(GenericAddress.parse(this.addressGet));
        target.setRetries(3);
        target.setTimeout(2000);
        return target;
    }
 
    private static PDU createPDU(int version, int type, String oid) {
        PDU pdu = null;
        if (version == SnmpConstants.version3) {
            pdu = new ScopedPDU();
        } else {
            pdu = new PDUv1();
        }
        pdu.setType(type);
        //可以添加多个变量oid
        /*for(String oid:oids){
            pdu.add(new VariableBinding(new OID(oid)));
        }*/
        pdu.add(new VariableBinding(new OID(oid)));
        return pdu;
    }
 
 
    /**
     * 这个方法有大用处,有时候我们查出的数据是35:32:30:30:30:30:30:30:30:31:31:37:31:30:32类似于这种格式,然后我们需要把它转为用户可识别的格式,就用它
     * @param octestString
     * @return
     */
    public static String getChinese(String octestString){
        try{
 
            String[] temps = octestString.split(":");
            byte[] bs = new byte[temps.length];
            for (int j=0;j< temps.length;j++){
                bs[j] = (byte)Integer.parseInt(temps[j],16);
            }
            return new String(bs,"GB2312");
        }catch (Exception e){
            return octestString;
        }
    }
    /**
     * WALK方式请求
     *功能简介:这个方法是getnext,就是遍历该oid下的所有子节点
     */
    public List<Map<String,Object>> snmpWalk() {
        try {
 
            List<Map<String,Object>> list = new ArrayList<>();
 
            //1、初始化snmp,并开启监听
            initSnmp();
            //2、创建目标对象
            Target target = createTarget(this.oid);
            //3、创建报文
            PDU pdu = createPDU(2, PDU.GETNEXT, this.oid);
            //4、发送报文,并获取返回结果
            boolean matched = true;
            while (matched) {
                ResponseEvent responseEvent = snmp.send(pdu, target);
                if (responseEvent == null || responseEvent.getResponse() == null) {
                    //LogUtil.info("snmp TimeOut...");
                    break;
                }
                PDU response = responseEvent.getResponse();
                String nextOid = null;
                Vector<? extends VariableBinding> variableBindings = response.getVariableBindings();
                for (int i = 0; i < variableBindings.size(); i++) {
 
                    VariableBinding variableBinding = variableBindings.elementAt(i);
                    Variable variable = variableBinding.getVariable();
                    nextOid = variableBinding.getOid().toDottedString();
                    //如果不是这个节点下的oid则终止遍历,否则会输出很多,直到整个遍历完。
                    if (!nextOid.startsWith(oid)) {
                        matched = false;
                        break;
                    }
                    Map<String,Object> map = new HashMap();
                    //放入oid以及oid对应获得的值
                    map.put(nextOid,variable);
                    list.add(map);
                }
                if (!matched) {
                    break;
                }
                pdu.clear();
                pdu.add(new VariableBinding(new OID(nextOid)));
            }
 
            System.out.println("list的大小 = " +list.size());
            return list;
 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
 
    public static List<Map<String,Object>> snmpWalk2(SnmpTestUtil snmpTestUtil) {
        try {
 
            List<Map<String,Object>> list = new ArrayList<>();
 
            //1、初始化snmp,并开启监听
            snmp = new Snmp(new DefaultUdpTransportMapping());
            //开启监听
            snmp.listen();
            //2、创建目标对象
            //先得到连接的ip和端口号
            String addressGet = "udp:" + snmpTestUtil.getHostIp()+"/"+snmpTestUtil.getHostPort();
 
            Target target = null;
            int version = 1;
            {
                //snmpV1和snmpV2需要指定团体名名称
                target = new CommunityTarget();
                ((CommunityTarget) target).setCommunity(new OctetString(snmpTestUtil.getCommunity()));
                if (version == SnmpConstants.version2c) {
                    target.setSecurityModel(SecurityModel.SECURITY_MODEL_SNMPv2c);
                }
            }
            target.setVersion(version);
            //必须指定,没有设置就会报错。
            target.setAddress(GenericAddress.parse(addressGet));
            target.setRetries(3);
            target.setTimeout(2000);
            //3、创建报文
            PDU pdu = createPDU(2, PDU.GETNEXT,"1.3.6.1.2.1.31.1.1.1.1");
            //4、发送报文,并获取返回结果
            boolean matched = true;
            while (matched) {
                ResponseEvent responseEvent = snmp.send(pdu, target);
                if (responseEvent == null || responseEvent.getResponse() == null) {
                    //LogUtil.info("snmp TimeOut...");
                    break;
                }
                PDU response = responseEvent.getResponse();
                String nextOid = null;
                Vector<? extends VariableBinding> variableBindings = response.getVariableBindings();
                for (int i = 0; i < variableBindings.size(); i++) {
 
                    VariableBinding variableBinding = variableBindings.elementAt(i);
                    Variable variable = variableBinding.getVariable();
                    nextOid = variableBinding.getOid().toDottedString();
                    //如果不是这个节点下的oid则终止遍历,否则会输出很多,直到整个遍历完。
                    if (!nextOid.startsWith("1.3.6.1.2.1.31.1.1.1.1")) {
                        matched = false;
                        break;
                    }
                    Map<String,Object> map = new HashMap();
                    //放入oid以及oid对应获得的值
                    map.put(nextOid,variable);
                    list.add(map);
                }
                if (!matched) {
                    break;
                }
                pdu.clear();
                pdu.add(new VariableBinding(new OID(nextOid)));
            }
 
            System.out.println("list的大小 = " +list.size());
            return list;
 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * 功能简介:获取单个节点oid对应的值
     * @throws IOException
     */
    public  void snmpGet( ) throws IOException {
 
 
        try {
 
            //1、初始化snmp,并开启监听
            initSnmp();
            //2、创建目标对象
            Target target = createTarget(this.oid);
            //3、创建报文
            PDU pdu = createPDU(2, PDU.GET, this.oid);
            //4、发送报文,并获取返回结果
 
 
            ResponseEvent responseEvent = snmp.send(pdu, target);
            PDU response = responseEvent.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 one OID value finished !");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("SNMP Get Exception:" + e);
        } finally {
            if (snmp != null) {
                try {
                    snmp.close();
                } catch (IOException ex1) {
                    snmp = null;
                }
            }
 
        }
    }
 
    public static void main(String[] args) {
        SnmpTestUtil snmpTestUtil = new SnmpTestUtil("192.168.8.150","161","public","1.3.6.1.2.1.31.1.1.1.1");
        List<Map<String, Object>> mapList = SnmpTestUtil.snmpWalk2(snmpTestUtil);
        Map<String,Integer> result = new HashMap<String,Integer>();
        int flat= 0;
        List<String> resultNeed = new ArrayList<>();
        for (Map<String, Object> map: mapList){
            for (String key:map.keySet()){
                System.out.println("key= "+key +" value= "+ map.get(key));
                //华为
                if (String.valueOf(map.get(key)).equals("9")){
                    String substring = key.substring(25, key.length());
                    resultNeed.add(substring);
                    System.out.println("找到我需要的数据了"+substring+"9");
                    break;
                }
 
            }
        }
        System.out.println("这是我需要的数据"+resultNeed.get(0));
 
    }
}