github address https://github.com/Plumblumpb/snmp-demo.git
Window environment configuration:https://jingyan.baidu.com/article/7f766dafe17d394101e1d0f9.html
linux environment configuration:https://blog.csdn.net/c_royi/article/details/86640800
pom.xml file
<dependency>
<groupId>org.snmp4j</groupId>
<artifactId>snmp4j</artifactId>
<version>2.5.11</version>
</dependency>
physical class (storage IP, port, version, and other information)
No display getter, setter method
**
* @Auther: cpb
* @Date: 2019/1/24 10:41
* @Description:
*/
public class SnmpModel {
private String communityName;
private String hostIp;
private Integer port;
private int version;
private int async;// Whether to query synchronously
private String serverId; // Monitoring server logo
private String code; // Code by the monitoring server
private String name; // Name of the monitoring server
private String type; // The application type of the server (such as application service, database service, front machine server), enter the input during maintenance, and present in the interface
private String systemName; // Monitoring server operating system
private String ip; // The IP address of the monitoring server
private String address; // Storage address of the monitoring service
private String statusid; // Status (1 is available, 0 is not available, and defaults to 1), whether to monitor this server
private String remark; // Remarks
private String cpu;
private String memory;
private String time;
private boolean ethernetConnection;
// Service Service field
private String serviceId; // Surveillance service logo
private String serviceName; // Monitoring service name
private String serverName; // The name of the server in the server
private String serverIp; // The monitoring service institute in the server IP
private String processeName; // The monitoring service is named
private String serviceStatus; // Status (1 is available, 0 is disabled, and the default value is 1), whether to monitor this service process
private String serviceRemark; // Remarks
}
SNMP service
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
/**
* @Auther: cpb
* @Date: 2019/1/24 10:42
* @Description:
*/
public class SnmpService {
private static final Logger logger = Logger.getLogger(SnmpService.class);
SnmpDao snmpDao = new SnmpDao();
public SnmpDao getInstanceSnmpDao() {
return snmpDao;
}
/**
* Get the CPU usage rate
*
* @param snmpmodel
* @Return to return to the current usage rate of CPU, otherwise return to -1
*/
public Integer getCpuUtilization(SnmpModel snmpModel) {
List<String> result = getInstanceSnmpDao().walkByTable(
".1.3.6.1.2.1.25.3.3.1.2", snmpModel);
if (result == null || result.size() == 0) {
return -1;
}
double sum = 0;
for (String s : result) {
sum += Double.parseDouble(s);
}
return (int) (sum / result.size());
}
/**
* Get Memory occupation rate
*
* @param snmpmodel
* @Return Back to the current memory usage normal, otherwise return to -1
* @throws ioException
*/
public Integer getMemoryUtilization(SnmpModel snmpModel){
// Use
try{
List<String> usedresultList = getInstanceSnmpDao().walkByTable(".1.3.6.1.2.1.25.2.3.1.6", snmpModel);
// Total
List<String> allresultList = getInstanceSnmpDao().walkByTable(".1.3.6.1.2.1.25.2.3.1.5", snmpModel);
if (usedresultList != null && usedresultList.size() > 0 && allresultList !=null && allresultList.size() >0) {
double used = 0;
// The last one is the memory (number of units in the unit) used by different machines due to the system
// System.out.println(usedresultList.size());
// for(String s:usedresultList){
// System.out.println(s);
// }
String usedStr = usedresultList.get(usedresultList.size() - 1);
used = Double.parseDouble(usedStr);
double all = 0;
String allStr = allresultList.get(allresultList.size() - 1);
all = Double.parseDouble(allStr);
return (int) ((used / all) * 100);
}
}catch (Exception e) {
logger.error("Get Memory occupancy rate:"+e.getMessage());
}
return -1;
}
/**
* The network is not similar to ping ip like ping ip
*
* @param snmpmodel
* @Return
* @throws ioException
*/
public boolean isEthernetConnection(SnmpModel snmpModel) throws IOException {
InetAddress ad = InetAddress.getByName(snmpModel.getHostIp());
boolean state = ad.isReachable(2000);// Test whether the address can reach the address 2 seconds overtime
return state;
}
}
SNMP implementation class
import org.apache.log4j.Logger;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @Auther: cpb
* @Date: 2019/1/24 10:43
* @Description:
*/
public class SnmpDao {
private String communityName;
private String hostIp;
private Integer port;
private int version;
private static final Logger logger = Logger.getLogger(SnmpDao.class);
/**
* Get the table value corresponding to the specified OID
* @param OID
* @param snmpmodel
* @Return
*/
public List<String> walkByTable(String oid, SnmpModel snmpModel){
//initSnmp(snmpModel);
Snmp snmp = null;
PDU pdu;
CommunityTarget target;
List<String> result = new ArrayList<String>();
communityName = snmpModel.getCommunityName();
hostIp = snmpModel.getHostIp();
port = snmpModel.getPort();
version = snmpModel.getVersion();
try {
DefaultUdpTransportMapping dm = new DefaultUdpTransportMapping();
// dm.setSocketTimeout(5000);
snmp = new Snmp(dm);
snmp.listen();
target = new CommunityTarget();
target.setCommunity(new OctetString(communityName));
target.setVersion(version);
target.setAddress(new UdpAddress(hostIp+"/"+port));
target.setTimeout(1000);
target.setRetries(1);
TableUtils tutils = new TableUtils(snmp, new DefaultPDUFactory(PDU.GETBULK));
OID[] columns = new OID[1];
columns[0] = new VariableBinding(new OID(oid)).getOid();
List<TableEvent> list = (List<TableEvent>) tutils.getTable(target, columns, null, null);
for(TableEvent e : list){
VariableBinding[] vb = e.getColumns();
if(null == vb)continue;
result.add(vb[0].getVariable().toString());
// System.out.println(vb[0].getVariable().toString());
}
snmp.close();
} catch (IOException e) {
//e.printStackTrace();
logger.error(e.getMessage());
}finally{
try {
if(snmp != null)
{
snmp.close();
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return result;
}
}
Method test
import java.io.IOException;
/**
* @Auther: cpb
* @Date: 2019/1/24 10:45
* @Description:
*/
public class Demo {
public static void main(String[] args) {
SnmpService snmpService = new SnmpService();
SnmpModel snmpModel = new SnmpModel();
snmpModel.setIp("127.0.0.1");
snmpModel.setCommunityName("public");
snmpModel.setHostIp("127.0.0.1");
snmpModel.setPort(161);
snmpModel.setVersion(1);
try {
// Whether to connect
System.out.println("Whether to connect:"+snmpService.isEthernetConnection(snmpModel));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("CPU utilization rate:"+ snmpService.getCpuUtilization(snmpModel));
System.out.println("Memory usage rate:"+ snmpService.getMemoryUtilization(snmpModel));
}
}