1.安装依赖
<dependency>
<groupId>org.snmp4j</groupId>
<artifactId>snmp4j</artifactId>
<version>2.5.11</version>
</dependency>
2.service代码,根据自己需要编写即可,下面示例:
import org.apache.log4j.Logger;
import org.immi.modules.snmp.entity.SnmpEntity;
import org.immi.modules.snmp.entity.dto.SnmpDto;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
/**
* @Auther: sn
* @Date:
* @Description:
*/
public class SnmpService {
private static final Loggerlogger = Logger.getLogger(SnmpService.class);
SnmpDtosnmpDto =new SnmpDto();
public SnmpDtogetInstanceSnmpDto() {
return snmpDto;
}
/**
* 获取CPU使用率
*
* @param
* @return 正常返回CPU当前使用率,否则返回-1
*/
public IntegergetCpuUtilization(SnmpEntity snmpEntity,String oid) {
List result = getInstanceSnmpDto().walkByTable(oid, snmpEntity);
if (result ==null || result.size() ==0) {
return -1;
}
double sum =0;
for (String s : result) {
// System.out.println("****Double值****"+Double.parseDouble(s));
sum += Double.parseDouble(s);
}
return (int) (sum / result.size());
}
/**
* 获取内存占用率
*
* @param snmpEntity
* @return 正常返回当前内存使用率,否则返回-1
* @throws IOException
*/
public IntegergetMemoryUtilization(SnmpEntity snmpEntity){
// 使用
try{
List usedresultList = getInstanceSnmpDto().walkByTable(".1.3.6.1.2.1.25.2.3.1.6", snmpEntity);
// 总
List allresultList = getInstanceSnmpDto().walkByTable(".1.3.6.1.2.1.25.2.3.1.5", snmpEntity);
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 snmpEntity
* @return
* @throws IOException
*/
public boolean isEthernetConnection(SnmpEntity snmpEntity)throws IOException {
InetAddress ad = InetAddress.getByName(snmpEntity.getHostIp());
boolean state = ad.isReachable(2000);// 测试是否可以达到该地址 2秒超时
return state;
}
/**
* 获取运行时间
* @param snmpEntity
* @return
*/
public StringgetTime(SnmpEntity snmpEntity,String oid) {
List result = getInstanceSnmpDto().walkByTable(oid, snmpEntity);
if (result ==null || result.size() ==0) {
return "未获取到运行日期";
}
for (String s : result) {
System.out.println("****运行日期****"+s);
return s;
}
return "获取失败";
}
/**
* 获取运行时间
* @param snmpEntity
* @return
*/
public ListflowIn(SnmpEntity snmpEntity,String oid) {
List result = getInstanceSnmpDto().walkByTable(oid, snmpEntity);
// System.out.println("****返回结果****"+result);
// if (result == null || result.size() == 0) {
//// return "-1";
// }
return result;
//// long sum = 0;
//// int sum = 0;
// for (String s : result) {
//// System.out.println("****单次流入****"+s);
//// sum += Double.parseDouble(s);
// sum += Long.parseLong(s);
// }
//// return sum;
}
}
3.Entity代码,主要放置了一些配置参数,根据需要编写即可,下为示例:
import javax.persistence.Entity;
import java.io.Serializable;
@Entity
public class SnmpEntityimplements Serializable {
private StringcommunityName;
private StringhostIp;
private Integerport;
private int version;
private int async;//是否同步查询
private StringserverId; // 受监控服务器标识
private Stringcode; // 受监控服务器编码
private Stringname; // 受监控服务器名称
private Stringtype; // 服务器的应用类型(如应用服务,数据库服务,前置机服务器),在维护时输入,在界面中相应字段呈现
private StringsystemName; // 受监控服务器操作系统
private Stringip; // 受监控服务器IP地址
private Stringaddress; // 受监控服务的存放地址
private Stringstatusid; // 状态(1为可用,0为不可用,默认为1),用于是否对这个服务器进行监控
private Stringremark; // 备注
private Stringcpu;
private Stringmemory;
private Stringtime;
private boolean ethernetConnection;
// 服务service字段
private StringserviceId; // 受监控服务标识
private StringserviceName; // 受监控服务名称
private StringserverName; // 受监控服务所在服务器名称
private StringserverIp; // 受监控服务所在服务器IP
private StringprocesseName; // 受监控服务进行名称
private StringserviceStatus; // 状态(1为可用,0为禁用,默认值为1),用于是否对这个服务进程进行监控
private StringserviceRemark; // 备注
public StringgetCommunityName() {
return communityName;
}
public void setCommunityName(String communityName) {
this.communityName = communityName;
}
public StringgetHostIp() {
return hostIp;
}
public void setHostIp(String hostIp) {
this.hostIp = hostIp;
}
public IntegergetPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public int getAsync() {
return async;
}
public void setAsync(int async) {
this.async = async;
}
public StringgetServerId() {
return serverId;
}
public void setServerId(String serverId) {
this.serverId = serverId;
}
public StringgetCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public StringgetName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public StringgetType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public StringgetSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public StringgetIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public StringgetAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public StringgetStatusid() {
return statusid;
}
public void setStatusid(String statusid) {
this.statusid = statusid;
}
public StringgetRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public StringgetCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public StringgetMemory() {
return memory;
}
public void setMemory(String memory) {
this.memory = memory;
}
public StringgetTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public boolean isEthernetConnection() {
return ethernetConnection;
}
public void setEthernetConnection(boolean ethernetConnection) {
this.ethernetConnection = ethernetConnection;
}
public StringgetServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public StringgetServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public StringgetServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public StringgetServerIp() {
return serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
public StringgetProcesseName() {
return processeName;
}
public void setProcesseName(String processeName) {
this.processeName = processeName;
}
public StringgetServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public StringgetServiceRemark() {
return serviceRemark;
}
public void setServiceRemark(String serviceRemark) {
this.serviceRemark = serviceRemark;
}
}
4.Dto代码
import org.apache.log4j.Logger;
import org.immi.modules.snmp.entity.SnmpEntity;
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: sn
* @Date:
* @Description:
*/
public class SnmpDto {
private StringcommunityName;
private StringhostIp;
private Integerport;
private int version;
private static final Loggerlogger = Logger.getLogger(SnmpDto.class);
/**
* 获取指定OID对应的table值
* @param oid
* @param snmpEntity
* @return
*/
public ListwalkByTable(String oid, SnmpEntity snmpEntity){
Snmp snmp =null;
PDU pdu;
CommunityTarget target;
List result =new ArrayList();
communityName = snmpEntity.getCommunityName();
hostIp = snmpEntity.getHostIp();
port = snmpEntity.getPort();
version = snmpEntity.getVersion();
try {
DefaultUdpTransportMapping dm =new DefaultUdpTransportMapping();
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);
pdu =new PDU();
pdu.setMaxRepetitions(50);
TableUtils tutils =new TableUtils(snmp, new DefaultPDUFactory(PDU.GETBULK));
OID[] columns =new OID[1];
columns[0] =new VariableBinding(new OID(oid)).getOid();
List list = (List) tutils.getTable(target, columns, null, null);
System.out.println("****输出结果****"+list);
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) {
logger.error(e.getMessage());
}finally{
try {
if(snmp !=null)
{
snmp.close();
}
}catch (IOException e) {
logger.error(e.getMessage());
}
}
return result;
}
}
5.调用
SnmpService snmpService =new SnmpService();
SnmpEntity snmpEntity =new SnmpEntity();
snmpEntity.setIp("0.0.0.0");//ip
snmpEntity.setCommunityName("admin");//社区编码
snmpEntity.setHostIp("0.0.0.0");
snmpEntity.setPort(161);//prot
snmpEntity.setVersion(SnmpConstants.version2c);//版本
System.out.println("是否连接:"+snmpService.isEthernetConnection(snmpEntity));
System.out.println("状态:"+ snmpService.flowIn(snmpEntity,".1.3.6.1.2.1.2.2.1.8"));//获取的状态,1是up,2是down
备注:
如果oid不是最终节点,将会自动递归获取所有节点直到最后一个节点,如果是最终节点,只会获取一条数据,并且在命令行中,如果不是最终节点命令只能使用:getnext oid,使用get将会报错,如果是最终节点,可以使用get oid,oid可以以:.0补充结尾或者不补充,对结果没有影响。