其实不用springboot我们也可以开发snmp采集,只是为了后面的需要我们才要用上springboot, 一开始可以直接用java就够了
先后尝试了vscode, idea老版,最后使用idea社区版与通义灵码来做这个事, 这事自己找个顺手的就好,只是我好久不弄,不得不先从搭开发环境开始
pom.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>snmpcli1</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>8</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.snmp4j</groupId>
<artifactId>snmp4j</artifactId>
<version>2.8.4</version>
</dependency>
</dependencies>
</project>
需要ctrl+shift+O 做下maven sync
Main.java
ini
package org.example;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
String address = "udp:192.168.10.252/161";
String community = "public";
String oid = "1.3.6.1.2.1.1.1.0";
try{
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
Snmp snmp = new Snmp(transport);
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(oid)));
pdu.setType(PDU.GET);
Address targetAddress = GenericAddress.parse(address);
Target target = new CommunityTarget(targetAddress, new OctetString(community));
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
ResponseEvent response = snmp.send(pdu, target);
PDU responsePDU = response.getResponse();
if (responsePDU!=null){
System.out.println("Response: " + responsePDU.get(0).getVariable());
}else {
System.out.println("Timeout");
}
snmp.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
OK shift+F10执行会得到结果
vbscript
Response: S5700-28C-EI
Huawei Versatile Routing Platform Software
VRP (R) software,Version 5.130 (S5700 V200R003C00SPC300)
Copyright (C) 2007 Huawei Technologies Co., Ltd.
Process finished with exit code 0