package com.sinosoft.common.utils;
import com.sinosoft.common.exception.BaseException;
import org.apache.commons.lang3.StringUtils;
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.text.DecimalFormat;
import java.util.*;
/**
* @Author zyq
* @Date 2020/7/3
* @Description: 使用snmp4j协议取得系统相关信息
*/
public class SnmpUtil {
private static Snmp snmp = null;
private static TransportMapping transport = null;
private static Address targetAddress = null;
private static PDU responsepdu = new PDU();
private static CommunityTarget target = null;
private static String ipStr = "";
/**
* 设置监控服务器地址
*
* @param ipStr
* @createTime 2020-07-03
*/
public static void setIpStr(String ipStr) {
SnmpUtil.ipStr = "udp:" + ipStr + "/161";
try {
initComm();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取当前服务器监控的IP地址
*
* @return
* @createTime 2020-07-03
*/
public static String getIpStr() {
if (StringUtils.isNotEmpty(ipStr) && ipStr.indexOf(":") != -1) {
ipStr = ipStr.split(":")[1].split("/161")[0];
}
return ipStr;
}
/**
* 初始化snmp监控信息
*
* @throws IOException
* @createTime 2020-07-03
*/
public static synchronized void initComm() throws IOException {
// 设置Agent方传输协议并打开监听
if (null != transport)
transport.close();
if (null != snmp)
snmp.close();
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
if (!transport.isListening())
transport.listen();
// 设置target
target = new CommunityTarget();
target.setCommunity(new OctetString("ubmp"));
targetAddress = GenericAddress.parse(ipStr);
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version1);
}
/**
* 获取CPU利用率 百分比
*
* @return
* @throws IOException
* @createTime 2020-6-30
*/
public static Map<String, Object> getCpuUse() throws Exception {
Map<String, Object> temMap = new HashMap<String, Object>();
try {
PDU responsepdu = new PDU();
responsepdu.add(new VariableBinding(new OID(
"1.3.6.1.2.1.25.3.3.1.2")));
responsepdu.setType(PDU.GETNEXT);
ResponseEvent response = snmp.send(responsepdu, target);
if (response.getResponse() == null) {
} else {
responsepdu = response.getResponse();
}
String tem = responsepdu.getVariableBindings().toString();
int temInt = 0;
if (tem.indexOf("Null") != -1) {
temInt = -1;
} else {
tem = tem.split("=")[1].split("]")[0].trim();
if (isNum(tem)) {
temInt = Integer.parseInt(tem);
}
}
temMap.put("cpuLoad", temInt);
} catch (Exception e) {
throw new BaseException("获取" + ipStr + &#