-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnmpBasicOperaton.java
More file actions
305 lines (238 loc) · 10.8 KB
/
Copy pathSnmpBasicOperaton.java
File metadata and controls
305 lines (238 loc) · 10.8 KB
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
package snmp;
/**
* Created by yuwang on 12/12/15.
* the snmpget/walk/set basic operation api class
* Support v1, v2c, and v3
*/
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
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.HashMap;
public class SnmpBasicOperaton {
private String ipAddress;
private String community;
private String port;
private int version; // should be 1, 2c, or 3
private int retires;
private int timeout;
public SnmpBasicOperaton(String ip, String communityString, int port, String versionString, int retries, int timeout) throws IllegalArgumentException {
this.ipAddress = ip;
this.community = communityString;
this.port = Integer.toString(port);
if (!versionString.equalsIgnoreCase("1") && !versionString.equalsIgnoreCase("2c") && !versionString.equalsIgnoreCase("3")) {
throw new IllegalArgumentException("The version string should be 1, 2c, or 3 in string type");
}
if (timeout >= 100000 || timeout < 500) {
throw new IllegalArgumentException("Timeout is too small or too long");
}
switch (versionString) {
case "1":
this.version = SnmpConstants.version1;
break;
case "2c":
this.version = SnmpConstants.version2c;
break;
case "3":
this.version = SnmpConstants.version3;
break;
default:
this.version = SnmpConstants.version1;
break;
}
this.retires = retries;
this.timeout = timeout;
}
public String snmpGet(String oid) throws IOException {
String result = "___NONE___";
// Create TransportMapping and Listen
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
// Create Target Address object
CommunityTarget comtarget = new CommunityTarget();
comtarget.setCommunity(new OctetString(this.community));
comtarget.setVersion(this.version);
comtarget.setAddress(new UdpAddress(this.ipAddress + "/" + this.port));
comtarget.setRetries(this.retires);
comtarget.setTimeout(this.timeout);
// Create the PDU object
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(oid)));
pdu.setType(PDU.GET);
pdu.setRequestID(new Integer32(1));
// Create Snmp object for sending data to Agent
Snmp snmp = new Snmp(transport);
//System.out.println("Sending Request to Agent...");
ResponseEvent response = snmp.get(pdu, comtarget);
// Process Agent Response
if (response != null) {
// System.out.println("Got Response from Agent");
PDU responsePDU = response.getResponse();
if (responsePDU != null) {
int errorStatus = responsePDU.getErrorStatus();
int errorIndex = responsePDU.getErrorIndex();
String errorStatusText = responsePDU.getErrorStatusText();
if (errorStatus == PDU.noError) {
result = responsePDU.getVariableBindings().firstElement().toString();
} 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: Response PDU is null");
}
} else {
System.out.println("Error: Agent Timeout... ");
}
snmp.close();
if (result.contains("=")) {
result = result.substring(result.indexOf("=") + 1, result.length()).trim();
}
// System.out.println(result); // for testing only, to pirnt out
return result;
}
public Boolean snmpSet(String target_oid, String target_value) throws IOException {
Boolean result = false;
// Create TransportMapping and Listen
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
// Create Target Address object
CommunityTarget comtarget = new CommunityTarget();
comtarget.setCommunity(new OctetString(this.community));
comtarget.setVersion(this.version);
comtarget.setAddress(new UdpAddress(this.ipAddress + "/" + this.port));
comtarget.setRetries(this.retires);
comtarget.setTimeout(this.timeout);
// Create the PDU object
PDU pdu = new PDU();
// Setting the Oid and Value for sysContact variable
OID oid = new OID(target_oid);
Variable var = new OctetString(target_value);
VariableBinding varBind = new VariableBinding(oid, var);
pdu.add(varBind);
pdu.setType(PDU.SET);
pdu.setRequestID(new Integer32(1));
// Create Snmp object for sending data to Agent
Snmp snmp = new Snmp(transport);
//
// System.out.println("\nRequest:\n[ Note: Set Request is sent for sysContact oid in RFC 1213 MIB.");
// System.out.println("Set operation will change the sysContact value to " + target_value);
// System.out.println("Once this operation is completed, Querying for sysContact will get the value = " + target_value + " ]");
//
// System.out.println("Request:\nSending Snmp Set Request to Agent...");
ResponseEvent response = snmp.set(pdu, comtarget);
// Process Agent Response
if (response != null) {
// System.out.println("\nResponse:\nGot Snmp Set Response from Agent");
PDU responsePDU = response.getResponse();
if (responsePDU != null) {
int errorStatus = responsePDU.getErrorStatus();
int errorIndex = responsePDU.getErrorIndex();
String errorStatusText = responsePDU.getErrorStatusText();
if (errorStatus == PDU.noError) {
System.out.println("Snmp Set Response = " + responsePDU.getVariableBindings());
result = true;
} 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);
result = false;
}
} else {
System.out.println("Error: Response PDU is null");
result = false;
}
} else {
System.out.println("Error: Agent Timeout... ");
result = false;
}
snmp.close();
return result;
}
public String[] snmpGetNext(String currentOid) throws Exception {
// System.out.println("SNMP GET-NEXT Demo");
String[] result = {"", ""};
String temp = "___NONE___"; // set ___NONE___ as initial value to avoid the real empty response from devices
// Create TransportMapping and Listen
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
// Create Target Address object
CommunityTarget comtarget = new CommunityTarget();
comtarget.setCommunity(new OctetString(this.community));
comtarget.setVersion(this.version);
comtarget.setAddress(new UdpAddress(this.ipAddress + "/" + this.port));
comtarget.setRetries(this.retires);
comtarget.setTimeout(this.timeout);
// Create the PDU object
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(currentOid))); //Querying GetNext of sysDescr will get the sysObjectID OID value
pdu.setRequestID(new Integer32(1));
pdu.setType(PDU.GETNEXT);
// Create Snmp object for sending data to Agent
Snmp snmp = new Snmp(transport);
ResponseEvent response = snmp.getNext(pdu, comtarget);
// Process Agent Response
if (response != null) {
//System.out.println("\nResponse:\nGot GetNext Response from Agent...");
PDU responsePDU = response.getResponse();
if (responsePDU != null) {
int errorStatus = responsePDU.getErrorStatus();
int errorIndex = responsePDU.getErrorIndex();
String errorStatusText = responsePDU.getErrorStatusText();
if (errorStatus == PDU.noError) {
temp = responsePDU.getVariableBindings().firstElement().toString();
} 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: GetNextResponse PDU is null");
}
} else {
System.out.println("Error: Agent Timeout... ");
}
snmp.close();
if (temp != "___NONE___" || temp.contains("=")) {
result[0] = "." + temp.substring(0, temp.indexOf("=")).trim(); // [0] is the next OID
result[1] = temp.substring(temp.indexOf("=") + 1, temp.length()).trim(); // [1] is the value of the next oid
}
// if (result[0].equalsIgnoreCase(currentOid)){
// throw new IllegalArgumentException("This OID has been the last one in the OID table");
// }
return result;
}
public HashMap<String, String> snmpWalk() throws Exception {
// Force the 2 times retries and 5s timeout in case of poor network
this.retires = 2;
this.timeout = 5000;
HashMap<String, String> walkResult = new HashMap<>();
final String startingOid = ".1.3.6.1.2.1.1.1.0";
walkResult.put(startingOid, snmpGet(startingOid));
String currentOid = startingOid;
while (true) {
if (snmpGet(currentOid) == "___NONE___") {
System.out.println(currentOid + " : break");
break;
}
String nextOid = snmpGetNext(currentOid)[0];
String nextValue = snmpGetNext(currentOid)[1];
if (nextValue.equalsIgnoreCase("endOfMibView")) {
break;
}
System.out.println(nextOid + " : " + nextValue);
currentOid = nextOid;
walkResult.put(nextOid, nextValue);
}
return walkResult;
}
}