java 通过服务器ip以及snmp协议读取cpu使用率,和内存使用率
github地址 https://github.com/Plumblumpb/snmp-demo.git
环境配置
window环境配置:https://jingyan.baidu.com/article/7f766dafe17d394101e1d0f9.html
linux环境配置:https://blog.csdn.net/c_royi/article/details/86640800
代码及运行流程
pom.xml文件
<dependency>
<groupId>org.snmp4j</groupId>
<artifactId>snmp4j</artifactId>
<version>2.5.11</version>
</dependency>
实体类(存储ip,port,version,等信息)
没有展示getter,setter方法
**
* @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;//是否同步查询
private String serverId; // 受监控服务器标识
private String code; // 受监控服务器编码
private String name; // 受监控服务器名称
private String type; // 服务器的应用类型(如应用服务,数据库服务,前置机服务器),在维护时输入,在界面中相应字段呈现
private String systemName; // 受监控服务器操作系统
private String ip; // 受监控服务器IP地址
private String address; // 受监控服务的存放地址
private String statusid; // 状态(1为可用,0为不可用,默认为1),用于是否对这个服务器进行监控
private String remark; // 备注
private String cpu;
private String memory;
private String time;
private boolean ethernetConnection;
// 服务service字段
private String serviceId; // 受监控服务标识
private String serviceName; // 受监控服务名称
private String serverName; // 受监控服务所在服务器名称
private String serverIp; // 受监控服务所在服务器IP
private String processeName; // 受监控服务进行名称
private String serviceStatus; // 状态(1为可用,0为禁用,默认值为1),用于是否对这个服务进程进行监控
private String serviceRemark; // 备注
}
snmp服务类
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;
}
/**
* 获取CPU使用率
*
* @param snmpModel
* @return 正常返回CPU当前使用率,否则返回-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());
}
/**
* 获取Memory占用率
*
* @param snmpModel
* @return 正常返回当前内存使用率,否则返回-1
* @throws IOException
*/
public Integer getMemoryUtilization(SnmpModel snmpModel){
// 使用
try{
List<String> usedresultList = getInstanceSnmpDao().walkByTable(".1.3.6.1.2.1.25.2.3.1.6", snmpModel);
// 总
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;
// 最后一个才是使用的内存(单位是数目 ) 因系统而不同 本机有5项
// 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("获取Memory占用率:"+e.getMessage());
}
return -1;
}
/**
* 测网络通不通 类似 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);// 测试是否可以达到该地址 2秒超时
return state;
}
}
snmp实现类
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);
/**
* 获取指定OID对应的table值
* @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;
}
}
方法测试
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 {
//是否连接
System.out.println("是否连接:"+snmpService.isEthernetConnection(snmpModel));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("cpu利用率:"+ snmpService.getCpuUtilization(snmpModel));
System.out.println("内存使用率:"+ snmpService.getMemoryUtilization(snmpModel));
}
}