我是靠谱客的博主 悦耳白昼,这篇文章主要介绍java+snmp调用(测试有效),现在分享给大家,希望可以做个参考。

建议 先去了解 snmp常识 ,不了解也不影响(替换oid就行)

1.环境(jdk1.8 +maven3)

主要jar包   snmp4j

复制代码
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
<modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.6</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.xu</groupId> <artifactId>xu</artifactId> <version>0.0.1-SNAPSHOT</version> <name>xu</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--SNMP简单网络协议--> <dependency> <groupId>org.snmp4j</groupId> <artifactId>snmp4j</artifactId> <version>2.8.3</version> </dependency> <!--SNMP简单网络协议--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

2.代码(测试代码,成功)

背景: 华三交换机  ,版本v2c有效(v3测试不成功)

常用oid  (百度以下都能找到,不常用的不清楚)

两种方式  ( 常量 的 **** 值替换成实际值,由于v2c版本有效,所以 把 

复制代码
1
//get 地址
复制代码
1
//trap 地址

注释处修改就ok,还有 团体名 修改成实际值

1.get方式

复制代码
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
/** * @description: get方式获取数据 * @author: yghhz * @create: 2020-11-15 10:14 **/ public class MultiThreadedGetDemo { private static final Logger LOGGER = LogManager.getLogger(MultiThreadedGetDemo.class); //用户名 private String username = "***************"; //鉴权密码 private String authPassword = "************!"; //数据加密密码 private String privPassword = "************!"; //trap地址 private String address = "udp:************/162"; //get 地址 private String addressGet = "udp:************/161"; private MultiThreadedMessageDispatcher dispatcher; private Snmp snmp = null; private Address listenAddress; private ThreadPool threadPool; public MultiThreadedGetDemo() { } public void initSnmp() throws IOException { //1、初始化多线程消息转发类 MessageDispatcher messageDispatcher = new MessageDispatcherImpl(); //其中要增加三种处理模型。如果snmp初始化使用的是Snmp(TransportMapping<? extends Address> transportMapping) ,就不需要增加 messageDispatcher.addMessageProcessingModel(new MPv1()); messageDispatcher.addMessageProcessingModel(new MPv2c()); //当要支持snmpV3版本时,需要配置user OctetString localEngineID = new OctetString(MPv3.createLocalEngineID()); USM usm = new USM(SecurityProtocols.getInstance().addDefaultProtocols(), localEngineID, 0); OctetString userName1 = new OctetString(username); OctetString authPass = new OctetString(authPassword); OctetString privPass = new OctetString(privPassword); UsmUser user = new UsmUser(userName1, AuthMD5.ID, authPass, PrivAES128.ID, privPass); usm.addUser(user.getSecurityName(), user); messageDispatcher.addMessageProcessingModel(new MPv3(usm)); //2、创建transportMapping ip为本地ip,可以不设置 TransportMapping<?> transportMapping = new DefaultUdpTransportMapping(); //3、正式创建snmp snmp = new Snmp(messageDispatcher, transportMapping); //开启监听 snmp.listen(); } private Target createTarget(String oid) { 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("******")); 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; } /** * GET方式请求 * @param oid */ public List<Map> snmpGet(String oid) { try { LOGGER.info("getfangshi"); List<Map> list = new ArrayList<Map>(); //1、初始化snmp,并开启监听 initSnmp(); //2、创建目标对象 Target target = this.createTarget(oid); //3、创建报文 PDU pdu = createPDU(1, PDU.GET, oid); //4、发送报文,并获取返回结果 ResponseEvent responseEvent = snmp.send(pdu, target); PDU response = responseEvent.getResponse(); if (response == null) { System.out.println("TimeOut..."); } else { if (response.getErrorStatus() == PDU.noError) { //get方式获取到的返回值 Vector<? extends VariableBinding> vbs = response.getVariableBindings(); for (VariableBinding vb : vbs) { Map map = new HashMap(); map.put("value",vb.getVariable()); System.out.println("vb.getVariable():" + vb.getVariable()); System.out.println("OID:" + vb.getVariable()); LOGGER.info("OIDvALUE" + vb.getVariable()); list.add(map); } return list; } else { System.out.println("Error:" + response.getErrorStatusText()); } } } catch (IOException e) { e.printStackTrace(); } return null; } //开启监控的main方法。 public static void main(String[] args) throws IOException { MultiThreadedGetDemo multithreadedtrapreceiver = new MultiThreadedGetDemo(); multithreadedtrapreceiver.run(); } public void run() { try { System.out.println("开始监听get信息!"); LOGGER.info("内存"); // String devOid = "1.3.6.1.4.1.25506.2.6.1.1.1.1.8"; String devOid = "1.3.6.1.2.1.1.5.0"; this.snmpGet(devOid); LOGGER.info("接口"); String devOid2 = "1.3.6.1.2.1.2.1.0"; // this.snmpGet(devOid2); // LOGGER.info("cpu"); // String devOid1 = "1.3.6.1.4.1.25506.2.6.1.1.1.1.6"; // this.snmpGet(devOid1); // LOGGER.info("运行时间"); // String data1 = "1.3.6.1.2.1.1.3.0"; // this.snmpGet(data1); } catch (Exception ex) { ex.printStackTrace(); } } }

2.walk

复制代码
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
@Slf4j public class MultiThreadedWalkDemo { private static final Logger LOGGER = LogManager.getLogger(MultiThreadedWalkDemo.class); //用户名 private String username = "m********er"; //鉴权密码 private String authPassword = "Te****************"; //数据加密密码 private String privPassword = "T********!"; //trap地址 private String address = "udp:********/162"; //get 地址 private String addressGet = "udp:********/161"; //get 地址 private String publicName = "*********"; // private String publicName = "********"; public Snmp snmp; public MultiThreadedWalkDemo() { } public void initSnmp() throws IOException { //1、初始化多线程消息转发类 MessageDispatcher messageDispatcher = new MessageDispatcherImpl(); //其中要增加三种处理模型。如果snmp初始化使用的是Snmp(TransportMapping<? extends Address> transportMapping) ,就不需要增加 messageDispatcher.addMessageProcessingModel(new MPv1()); messageDispatcher.addMessageProcessingModel(new MPv2c()); //当要支持snmpV3版本时,需要配置user OctetString localEngineID = new OctetString(MPv3.createLocalEngineID()); USM usm = new USM(SecurityProtocols.getInstance().addDefaultProtocols(), localEngineID, 0); OctetString userName1 = new OctetString(username); OctetString authPass = new OctetString(authPassword); OctetString privPass = new OctetString(privPassword); UsmUser user = new UsmUser(userName1, AuthMD5.ID, authPass, PrivAES128.ID, privPass); usm.addUser(user.getSecurityName(), user); messageDispatcher.addMessageProcessingModel(new MPv3(usm)); //2、创建transportMapping ip为本地ip,可以不设置 TransportMapping<?> transportMapping = new DefaultUdpTransportMapping(); // UdpAddress updAddr = (UdpAddress) GenericAddress.parse("udp:172.29.12.95/161"); // TransportMapping<?> transportMapping = new DefaultUdpTransportMapping(updAddr); //3、正式创建snmp snmp = new Snmp(messageDispatcher, transportMapping); //开启监听 snmp.listen(); } private Target createTarget(String oid,int version) { 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.username)); ((CommunityTarget) target).setCommunity(new OctetString(publicName)); if (version == SnmpConstants.version2c) { target.setVersion(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; } /** * WALK方式请求 * @param oid */ public void snmpWalk(String oid,int version) { try { LOGGER.info("walkfangshi"); List<Map> list = new ArrayList<Map>(); //1、初始化snmp,并开启监听 initSnmp(); //2、创建目标对象 Target target = createTarget(oid,version); //3、创建报文 // PDU pdu = createPDU(1, PDU.GETNEXT, oid); PDU pdu = createPDU(version, PDU.GETNEXT, oid); //4、发送报文,并获取返回结果 boolean matched = true; while (matched) { ResponseEvent responseEvent = snmp.send(pdu, target); // ResponseEvent responseEvent = snmp.getNext(pdu, target); if (responseEvent == null || responseEvent.getResponse() == null) { System.out.println("TimeOut..."); break; } PDU response = responseEvent.getResponse(); String nextOid = null; Vector<? extends VariableBinding> variableBindings = response.getVariableBindings(); for (int i = 0; i < variableBindings.size(); i++) { Map map = new HashMap(); VariableBinding variableBinding = variableBindings.elementAt(i); Variable variable = variableBinding.getVariable(); nextOid = variableBinding.getOid().toDottedString(); // System.out.println("oid:" + nextOid + ",value:" + variable); //如果不是这个节点下的oid则终止遍历,否则会输出很多,直到整个遍历完。 if (!nextOid.startsWith(oid)) { matched = false; break; } map.put("oid", nextOid); map.put("value",variable); list.add(map); System.out.println("oid:" + nextOid + ",value:" + variable); LOGGER.info("oid:" + nextOid + ",value:" + variable); } if (!matched) { break; } pdu.clear(); pdu.add(new VariableBinding(new OID(nextOid))); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //开启监控的main方法。 public static void main(String[] args) throws IOException, InterruptedException { MultiThreadedWalkDemo multithreadedtrapreceiver = new MultiThreadedWalkDemo(); multithreadedtrapreceiver.run(); // Thread.sleep(5000); // multithreadedtrapreceiver.run(); } public void run() { try { LOGGER.info("开始监听walk信息!"); // LOGGER.info("开始获取端口名称!"); // String healthOID1 = "1.3.6.1.2.1.2.2.1.2.0"; String healthOID1 = "1.3.6.1.2.1.2.2.1.2"; // this.snmpWalk(healthOID1); // LOGGER.info("网口流量"); // String healthOID2 = "1.3.6.1.2.1.2.2.1.10.0"; // this.snmpWalk(healthOID2); // LOGGER.info("网口状态"); // String healthOID3 = "1.3.6.1.2.1.2.2.1.16.0"; // this.snmpWalk(healthOID3); // LOGGER.info("网口速率"); String healthOID4 = "1.3.6.1.2.1.2.2.1.16"; // String healthOID4 = "1.3.6.1.2.1.2.2.1.5"; // String healthOID4 = "1.3.6.1.2.1.2.2.1.16"; // String healthOID4 = "1.3.6.1.2.1.2.2.1.3"; this.snmpWalk(healthOID4,1); // LOGGER.info("网口速率"); // String healthOID5 = "1.3.6.1.2.1.31.1.1.1.15"; // this.snmpWalk(healthOID5); } catch (Exception ex) { ex.printStackTrace(); } } }

最后

以上就是悦耳白昼最近收集整理的关于java+snmp调用(测试有效)的全部内容,更多相关java+snmp调用(测试有效)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部