snmp 协议开发之SNMP4J 简单封装
小虾米
阅读:1396
2021-03-31 22:26:07
评论:0
源代码项目结构:
snmp.comm包:主要展示OID 和对应的实体对象
snmp_conf.properties配置文件
# ROOT OID
# Internet Part
snmp_public_pre=.1.3.6.1.2.1
# Enterprise Part
snmp_private_pre=.1.3.6.1.4.1
#私有OID
2021
311 Mircosoft
6876 VMware
DEVICE_CPU_ID=1.3.6.1.2.1.25.3.1.3
DEVICE_DISK_ID=1.3.6.1.2.1.25.2.1.4
DEVICE_STORAGE_RAM_ESXi_ID=1.3.6.1.2.1.25.2.1.20
DEVICE_RAM_DISK_ID=1.3.6.1.2.1.25.2.1.8
DEVICE_NETWORK_DISK_ID=1.3.6.1.2.1.25.2.1.10
DEVICE_STORAGE_RAM_ID=1.3.6.1.2.1.25.2.1.2
#Windows OID
#------------------------------------------Memory Info---------------------------------------------------
walk.window.memory.physical.used=.1.3.6.1.2.1.25.2.3.1.6
#------------------------------------------Disk Info----------------------------------------------------
walk.window.disk.index=.1.3.6.1.2.1.25.2.3.1.1
walk.window.disk.type=.1.3.6.1.2.1.25.2.3.1.2
walk.window.disk.desc=.1.3.6.1.2.1.25.2.3.1.3
walk.window.disk.amount=.1.3.6.1.2.1.25.2.3.1.4
walk.window.disk.size=.1.3.6.1.2.1.25.2.3.1.5
walk.window.disk.used=.1.3.6.1.2.1.25.2.3.1.6
#Linux OID
#------------------------------------PRIVATE CPU INFO----------------------------------------------------
get.linux.user.cpu.rate=.1.3.6.1.4.1.2021.11.9.0
get.linux.system.cpu.rate=.1.3.6.1.4.1.2021.11.10.0
get.linux.free.cpu.rate=.1.3.6.1.4.1.2021.11.11.0
#------------------------------------DISK INFO-----------------------------------------------------------
walk.linux.disk.index=.1.3.6.1.4.1.2021.9.1.2
walk.linux.disk.size=.1.3.6.1.4.1.2021.9.1.6
walk.linux.disk.free.size=.1.3.6.1.4.1.2021.9.1.7
walk.linux.disk.used.size=.1.3.6.1.4.1.2021.9.1.8
walk.linux.disk.used.rate=.1.3.6.1.4.1.2021.9.1.9
#Common OID
#-----------------------------------------------System Info----------------------------------------------
get.system.description=.1.3.6.1.2.1.1.1.0
get.system.uptime=.1.3.6.1.2.1.1.3.0
get.system.contact=.1.3.6.1.2.1.1.4.0
get.system.name=.1.3.6.1.2.1.1.5.0
get.system.location=.1.3.6.1.2.1.1.6.0
#----------------------------------NetWork Information---------------------------------------------------
get.network.interface.number=.1.3.6.1.2.1.2.1.0
walk.network.interface.index=.1.3.6.1.2.1.2.2.1.1
walk.network.interface.desc=.1.3.6.1.2.1.2.2.1.2
walk.network.interface.type=.1.3.6.1.2.1.2.2.1.3
walk.network.interface.speed=.1.3.6.1.2.1.2.2.1.5
walk.network.interface.physicalAddress=.1.3.6.1.2.1.2.2.1.6
walk.network.interface.recieve.byte=.1.3.6.1.2.1.2.2.1.10
walk.network.interface.send.byte=.1.3.6.1.2.1.2.2.1.11
walk.network.interface.recieve.packet=.1.3.6.1.2.1.2.2.1.12
walk.network.interface.send.packet=.1.3.6.1.2.1.2.2.1.13
#------------------------------------Memory Information--------------------------------------------------
get.memory.total.physical=.1.3.6.1.2.1.25.2.2.0
#------------------------------------CPU Information-----------------------------------------------------
walk.device.index=.1.3.6.1.2.1.25.3.2.1.1
walk.device.type=.1.3.6.1.2.1.25.3.2.1.2
walk.device.info=.1.3.6.1.2.1.25.3.2.1.3
walk.cpu.current.load.index=.1.3.6.1.2.1.25.3.3.1.2
SnmpProperties.java 实体对象
package com.emc.snmp.comm;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.jar.JarFile;
import java.util.jar.JarEntry;
/**
* Created by Ouwei on 14-5-26.
* SnmpOID配置文件读取类
*/
public class SnmpProperties {
private static SnmpProperties snmpProperties = null;
private String sysDesc;
private String sysUptime;
private String sysName;
private String sysContact;
private String sysLocation;
private String cpuID;
private String hrStorageFixedDisk;
private String hrStorageRamDisk;
private String hrStorageNetWorkDisk;
private String ramID;
private String exiRamID;
private String windowUsedMemory;
private String windowDiskIndex;
private String windowDiskType;
private String windowDiskDesc;
private String windowDiskAmount;
private String windowDiskUsed;
private String windowDiskSize;
private String linuxUserCPURate;
private String linuxSysCPURate;
private String linuxFreeCPURate;
private String linuxDiskIndex;
private String linuxDiskUsed;
private String linuxDiskFree;
private String linuxDiskSize;
private String linxuDiskUsedRate;
private String networkNumber;
private String networkType;
private String networkIndex;
private String networkDesc;
private String networkSpeed;
private String networkPhysicalAddr;
private String networkRecieveByte;
private String networkSendByte;
private String networkRecievePacket;
private String networkSendPacket;
private String memoryTotalSize;
private String deviceIndex;
private String deviceType;
private String deviceInfo;
private String cpuCurrentLoadIndex;
public String getExiRamID() {
return exiRamID;
}
public String getRamID() {
return ramID;
}
public String getWindowDiskType() {
return windowDiskType;
}
public String getWindowDiskDesc() {
return windowDiskDesc;
}
public String getLinuxDiskIndex() {
return linuxDiskIndex;
}
public String getLinuxDiskUsed() {
return linuxDiskUsed;
}
public String getLinuxDiskFree() {
return linuxDiskFree;
}
public String getLinuxDiskSize() {
return linuxDiskSize;
}
public String getLinxuDiskUsedRate() {
return linxuDiskUsedRate;
}
public String getSysDesc() {
return sysDesc;
}
public String getSysUptime() {
return sysUptime;
}
public String getSysName() {
return sysName;
}
public String getSysContact() {
return sysContact;
}
public String getSysLocation() {
return sysLocation;
}
public String getCpuID() {
return cpuID;
}
public String getWindowUsedMemory() {
return windowUsedMemory;
}
public String getWindowDiskIndex() {
return windowDiskIndex;
}
public String getWindowDiskAmount() {
return windowDiskAmount;
}
public String getWindowDiskUsed() {
return windowDiskUsed;
}
public String getWindowDiskSize() {
return windowDiskSize;
}
public String getLinuxUserCPURate() {
return linuxUserCPURate;
}
public String getLinuxSysCPURate() {
return linuxSysCPURate;
}
public String getLinuxFreeCPURate() {
return linuxFreeCPURate;
}
public String getNetworkNumber() {
return networkNumber;
}
public String getNetworkType() {
return networkType;
}
public String getNetworkIndex() {
return networkIndex;
}
public String getNetworkDesc() {
return networkDesc;
}
public String getNetworkSpeed() {
return networkSpeed;
}
public String getNetworkPhysicalAddr() {
return networkPhysicalAddr;
}
public String getNetworkRecieveByte() {
return networkRecieveByte;
}
public String getNetworkSendByte() {
return networkSendByte;
}
public String getNetworkRecievePacket() {
return networkRecievePacket;
}
public String getNetworkSendPacket() {
return networkSendPacket;
}
public String getMemoryTotalSize() {
return memoryTotalSize;
}
public String getDeviceIndex() {
return deviceIndex;
}
public String getDeviceType() {
return deviceType;
}
public String getDeviceInfo() {
return deviceInfo;
}
public String getCpuCurrentLoadIndex() {
return cpuCurrentLoadIndex;
}
public String getHrStorageFixedDisk() {
return hrStorageFixedDisk;
}
public String getHrStorageRamDisk() {
return hrStorageRamDisk;
}
public String getHrStorageNetWorkDisk() {
return hrStorageNetWorkDisk;
}
public static SnmpProperties loadProperties() {
if (snmpProperties != null)
return snmpProperties;
else {
String strPath = SnmpProperties.class.getResource("").toString();
//int preIndex = ("jar:file:/").length();
//int endIndex = strPath.indexOf("BASE-1.0-SNAPSHOT.jar!/com/emc/snmp/comm/");
//strPath = strPath.substring(preIndex,endIndex);
HashMap<String,String> hashMap = new HashMap<String,String>();
try {
//JarFile jarFile = new JarFile(strPath + "BASE-1.0-SNAPSHOT.jar");
//JarEntry entry = jarFile.getJarEntry("snmp_conf.properties");
InputStream is = SnmpProperties.class.getResourceAsStream("snmp_conf.properties");
// InputStream input = jarFile.getInputStream(entry);
Properties dbProps = new Properties();
//dbProps.load(input);
dbProps.load(is);
//---------------BASE SYSTEM INFORMATION-----------
hashMap.put("SYSDESC", dbProps.getProperty("get.system.description"));
hashMap.put("SYSUPTIME", dbProps.getProperty("get.system.uptime"));
hashMap.put("SYSCONTACT", dbProps.getProperty("get.system.contact"));
hashMap.put("SYSLOCATION", dbProps.getProperty("get.system.name"));
hashMap.put("SYSNAME", dbProps.getProperty("get.system.location"));
hashMap.put("CPUID",dbProps.getProperty("DEVICE_CPU_ID"));
hashMap.put("HR_STORAGE_FIXED_DISK",dbProps.getProperty("DEVICE_DISK_ID"));
hashMap.put("HR_STORAGE_RAM_DISK",dbProps.getProperty("DEVICE_RAM_DISK_ID"));
hashMap.put("HR_STORAGE_NETWORK_DISK",dbProps.getProperty("DEVICE_NETWORK_DISK_ID"));
hashMap.put("HR_STORAGE_RAM_ID",dbProps.getProperty("DEVICE_STORAGE_RAM_ID"));
hashMap.put("HR_STORIAGE_RAM_EXI_ID",dbProps.getProperty("DEVICE_STORAGE_RAM_ESXi_ID"));
//---------------Memory Information------------------------------------
hashMap.put("MEMORY_SIZE",dbProps.getProperty("get.memory.total.physical"));
//---------------------------NetWork Information-------------------------------------
hashMap.put("NETWORK_NUMBER",dbProps.getProperty("get.network.interface.number"));
hashMap.put("NETWORK_INDEX",dbProps.getProperty("walk.network.interface.index"));
hashMap.put("NETWORK_DESC",dbProps.getProperty("walk.network.interface.desc"));
hashMap.put("NETWORK_TYPE",dbProps.getProperty("walk.network.interface.type"));
hashMap.put("NETWORK_SPEED",dbProps.getProperty("walk.network.interface.speed"));
hashMap.put("NETWORK_PHYSICAL_ADDR",dbProps.getProperty("walk.network.interface.physicalAddress"));
hashMap.put("NETWORK_REC_BYTE",dbProps.getProperty("walk.network.interface.recieve.byte"));
hashMap.put("NETWORK_SEND_BYTE",dbProps.getProperty("walk.network.interface.send.byte"));
hashMap.put("NETWORK_REC_PACKET",dbProps.getProperty("walk.network.interface.recieve.packet"));
hashMap.put("NETWORK_SEND_PACKET",dbProps.getProperty("walk.network.interface.send.packet"));
//----------------------------CPU Information----------------------------------------
hashMap.put("DEVICE_INDEX",dbProps.getProperty("walk.device.index"));
hashMap.put("DEVICE_TYPE",dbProps.getProperty("walk.device.type"));
hashMap.put("DEVICE_INFO",dbProps.getProperty("walk.device.info"));
hashMap.put("CPU_LOAD",dbProps.getProperty("walk.cpu.current.load.index"));
//-----------------PRIVATE WINDOWS OID---------------------------------------------
-----------------DISK INFORMATION------------------------------------
hashMap.put("WINDOW_DISK_INDEX",dbProps.getProperty("walk.window.disk.index"));
hashMap.put("WINDOW_DISK_AMOUNT",dbProps.getProperty("walk.window.disk.amount"));
hashMap.put("WINDOW_DISK_SIZE",dbProps.getProperty("walk.window.disk.size"));
hashMap.put("WINDOW_DISK_USED",dbProps.getProperty("walk.window.disk.used"));
hashMap.put("WINDOW_DISK_DESC",dbProps.getProperty("walk.window.disk.desc"));
hashMap.put("WINDOW_DISK_TYPE", dbProps.getProperty("walk.window.disk.type"));
---------------------Memory Information------------------------------------------
hashMap.put("WINDOW_MEMORY_USED",dbProps.getProperty("walk.window.memory.physical.used"));
//-----------------------PRIVATE LINUX OID------------------------------------------
hashMap.put("LINUX_USER",dbProps.getProperty("get.linux.user.cpu.rate"));
hashMap.put("LINUX_SYS",dbProps.getProperty("get.linux.system.cpu.rate"));
hashMap.put("LINUX_FREE",dbProps.getProperty("get.linux.free.cpu.rate"));
hashMap.put("LINUX_DISK_INDEX",dbProps.getProperty("walk.linux.disk.index"));
hashMap.put("LINUX_DISK_SIZE",dbProps.getProperty("walk.linux.disk.size"));
hashMap.put("LINUX_DISK_FREE",dbProps.getProperty("walk.linux.disk.free.size"));
hashMap.put("LINUX_DISK_USED",dbProps.getProperty("walk.linux.disk.used.size"));
hashMap.put("LINUX_DISK_USED_RATE",dbProps.getProperty("walk.linux.disk.used.rate"));
}catch(Exception e) {
e.printStackTrace();
}
return new SnmpProperties(hashMap);
}
}
private SnmpProperties(HashMap<String,String> hashMap) {
this.sysDesc = hashMap.get("SYSDESC");
this.sysUptime = hashMap.get("SYSUPTIME");
this.sysContact = hashMap.get("SYSCONTACT");
this.sysLocation = hashMap.get("SYSLOCATION");
this.sysName = hashMap.get("SYSNAME");
this.cpuID = hashMap.get("CPUID");
this.hrStorageFixedDisk = hashMap.get("HR_STORAGE_FIXED_DISK");
this.hrStorageRamDisk = hashMap.get("HR_STORAGE_RAM_DISK");
this.hrStorageNetWorkDisk = hashMap.get("HR_STORAGE_NETWORK_DISK");
this.ramID = hashMap.get("HR_STORAGE_RAM_ID");
this.exiRamID = hashMap.get("HR_STORIAGE_RAM_EXI_ID");
this.memoryTotalSize = hashMap.get("MEMORY_SIZE");
this.cpuCurrentLoadIndex = hashMap.get("CPU_LOAD");
this.deviceIndex = hashMap.get("DEVICE_INDEX");
this.deviceInfo = hashMap.get("DEVICE_INFO");
this.deviceType = hashMap.get("DEVICE_TYPE");
this.linuxFreeCPURate = hashMap.get("LINUX_FREE");
this.linuxSysCPURate = hashMap.get("LINUX_SYS");
this.linuxUserCPURate = hashMap.get("LINUX_USER");
this.windowDiskAmount = hashMap.get("WINDOW_DISK_AMOUNT");
this.windowDiskIndex = hashMap.get("WINDOW_DISK_INDEX");
this.windowDiskType = hashMap.get("WINDOW_DISK_TYPE");
this.windowDiskSize = hashMap.get("WINDOW_DISK_SIZE");
this.windowDiskUsed = hashMap.get("WINDOW_DISK_USED");
this.windowDiskDesc = hashMap.get("WINDOW_DISK_DESC");
this.windowUsedMemory = hashMap.get("WINDOW_MEMORY_USED");
this.networkDesc = hashMap.get("NETWORK_DESC");
this.networkIndex = hashMap.get("NETWORK_INDEX");
this.networkNumber = hashMap.get("NETWORK_NUMBER");
this.networkPhysicalAddr = hashMap.get("NETWORK_PHYSICAL_ADDR");
this.networkRecieveByte = hashMap.get("NETWORK_REC_BYTE");
this.networkRecievePacket = hashMap.get("NETWORK_REC_PACKET");
this.networkSendByte = hashMap.get("NETWORK_SEND_BYTE");
this.networkSendPacket = hashMap.get("NETWORK_SEND_PACKET");
this.networkSpeed = hashMap.get("NETWORK_SPEED");
this.networkType = hashMap.get("NETWORK_TYPE");
this.linuxDiskFree = hashMap.get("LINUX_DISK_FREE");
this.linuxDiskIndex = hashMap.get("LINUX_DISK_INDEX");
this.linuxDiskSize = hashMap.get("LINUX_DISK_SIZE");
this.linuxDiskUsed = hashMap.get("LINUX_DISK_USED");
this.linxuDiskUsedRate = hashMap.get("LINUX_DISK_USED_RATE");
}
}
snmp.info:采集设备对应实体对象
CpuInfo.java :采集CPU实体对象
package com.emc.snmp.info;
import java.util.ArrayList;
/**
* Created by Ouwei on 14-5-26.
* CPU信息基本类
*/
public class CpuInfo {
private String cpuDesc; // cpu信息描述
private int coreNum; // cpu核数
private String userRate; // cpu使用率
private String sysRate;
private String freeRate; // cpu空闲率
private ArrayList<CpuInfo> cpuDetailInfos; // 每个核的信息
public ArrayList<CpuInfo> getCpuDetailInfos() {
return cpuDetailInfos;
}
public void setCpuDetailInfos(ArrayList<CpuInfo> cpuDetailInfos) {
this.cpuDetailInfos = cpuDetailInfos;
}
public String getUserRate() {
return userRate;
}
public void setUserRate(String userRate) {
this.userRate = userRate;
}
public String getSysRate() {
return sysRate;
}
public void setSysRate(String sysRate) {
this.sysRate = sysRate;
}
public String getFreeRate() {
return freeRate;
}
public void setFreeRate(String freeRate) {
this.freeRate = freeRate;
}
public int getCoreNum() {
return coreNum;
}
public void setCoreNum(int coreNum) {
this.coreNum = coreNum;
}
public String getCpuDesc() {
return cpuDesc;
}
public void setCpuDesc(String cpuDesc) {
this.cpuDesc = cpuDesc;
}
}
DiskInfo.java :采集Disk实体对象
package com.emc.snmp.info;
/**
* Created by Ouwei on 14-5-26.
* 硬盘信息基础类
*/
public class DiskInfo {
private String diskName; // 盘符
private String diskLabel; // 卷标名
private String diskSN; // 序列号
private String diskSize; // 硬盘容量
private String diskFreeSize; // 硬盘空闲容量
private String diskUsedSize; // 硬盘已用容量
private double percentUsed; // 硬盘已用百分比
private String diskDesc; // 硬盘描述
public String getDiskDesc() {
return diskDesc;
}
public void setDiskDesc(String diskDesc) {
this.diskDesc = diskDesc;
}
public String getDiskName() {
return diskName;
}
public void setDiskName(String diskName) {
this.diskName = diskName;
}
public String getDiskLabel() {
return diskLabel;
}
public void setDiskLabel(String diskLabel) {
this.diskLabel = diskLabel;
}
public String getDiskSN() {
return diskSN;
}
public void setDiskSN(String diskSN) {
this.diskSN = diskSN;
}
public String getDiskSize() {
return diskSize;
}
public void setDiskSize(String diskSize) {
this.diskSize = diskSize;
}
public String getDiskFreeSize() {
return diskFreeSize;
}
public void setDiskFreeSize(String diskFreeSize) {
this.diskFreeSize = diskFreeSize;
}
public String getDiskUsedSize() {
return diskUsedSize;
}
public void setDiskUsedSize(String diskUsedSize) {
this.diskUsedSize = diskUsedSize;
}
public double getPercentUsed() {
return percentUsed;
}
public void setPercentUsed(double percentUsed) {
this.percentUsed = percentUsed;
}
}
MemoryInfo.java:采集Memory基础信息
package com.emc.snmp.info;
/**
* Created by Ouwei on 14-5-26.
* 内存信息基本类
*/
public class MemoryInfo {
private String memorySize; // 内存总大小 (单位G)
private String memoryFreeSize; // 内存空闲量 (单位G)
private String memoryUsedSize; // 内存使用量 (单位G)
private String memoryPercentage; // 内存使用率
public String getMemorySize() {
return memorySize;
}
public void setMemorySize(String memorySize) {
this.memorySize = memorySize;
}
public String getMemoryFreeSize() {
return memoryFreeSize;
}
public void setMemoryFreeSize(String memoryFreeSize) {
this.memoryFreeSize = memoryFreeSize;
}
public String getMemoryUsedSize() {
return memoryUsedSize;
}
public void setMemoryUsedSize(String memoryUsedSize) {
this.memoryUsedSize = memoryUsedSize;
}
public String getMemoryPercentage() {
return memoryPercentage;
}
public void setMemoryPercentage(String memoryPercentage) {
this.memoryPercentage = memoryPercentage;
}
}
SystemInfo.java:采集SystemInfo 基础信息
package com.emc.snmp.info;
import java.util.ArrayList;
/**
* Created by Ouwei on 14-5-26.
* 系统信息基础类(包括CPU,内存,硬盘信息)
*/
public class SystemInfo {
private String sysDesc; // 系统描述
private String sysUpTime; // 系统运行时间(单位:秒)
private String sysContact; // 系统联系人
private String sysName; // 计算机名
private String sysLocation; // 计算机位置
private MemoryInfo memoryInfo; // 计算机内存信息
private ArrayList<DiskInfo> diskInfos; // 计算机硬盘信息
private CpuInfo cpuInfo; // cpu信息
public CpuInfo getCpuInfo() {
return cpuInfo;
}
public void setCpuInfo(CpuInfo cpuInfo) {
this.cpuInfo = cpuInfo;
}
public String getSysDesc() {
return sysDesc;
}
public void setSysDesc(String sysDesc) {
this.sysDesc = sysDesc;
}
public String getSysUpTime() {
return sysUpTime;
}
public void setSysUpTime(String sysUpTime) {
this.sysUpTime = sysUpTime;
}
public String getSysContact() {
return sysContact;
}
public void setSysContact(String sysContact) {
this.sysContact = sysContact;
}
public String getSysName() {
return sysName;
}
public void setSysName(String sysName) {
this.sysName = sysName;
}
public String getSysLocation() {
return sysLocation;
}
public void setSysLocation(String sysLocation) {
this.sysLocation = sysLocation;
}
public MemoryInfo getMemoryInfo() {
return memoryInfo;
}
public void setMemoryInfo(MemoryInfo memoryInfo) {
this.memoryInfo = memoryInfo;
}
public ArrayList<DiskInfo> getDiskInfos() {
return diskInfos;
}
public void setDiskInfos(ArrayList<DiskInfo> diskInfos) {
this.diskInfos = diskInfos;
}
public String toString() {
StringBuffer info = new StringBuffer();
info.append("The System Base Info: \n SysDesc: " + this.getSysDesc()
+ "\n SysName: " + this.getSysName() + "\n SysUptime: "
+ this.getSysUpTime() + "\n SysContact: "
+ this.getSysContact() + "\n SysLocation: "
+ this.getSysLocation() + "\n");
info.append("The Memory Info: \n Memory Size: " + this.getMemoryInfo().getMemorySize()
+ "\n Memory Free Size: " + this.getMemoryInfo().getMemoryFreeSize()
+ "\n Memory Used Size: " + this.getMemoryInfo().getMemoryUsedSize()
+ "\n Memory Used Percentage: " + this.getMemoryInfo().getMemoryPercentage() + "\n");
info.append("The Disk Info: \n");
info.append(this.diskInfotoString());
info.append("The CPU Info: \n");
info.append(this.cpuInfotoString());
return info.toString();
}
private String cpuInfotoString() {
StringBuffer cpuInfoStr = new StringBuffer();
CpuInfo cpuInfo = this.getCpuInfo();
ArrayList<CpuInfo> cpuInfos = cpuInfo.getCpuDetailInfos();
for (int i=0;i<cpuInfos.size();i++) {
CpuInfo obj = cpuInfos.get(i);
cpuInfoStr.append("Cpu Desc: " + obj.getCpuDesc() + "\n");
}
cpuInfoStr.append("The Number of core CPU : " + cpuInfo.getCoreNum()
+ "\nSystem Rate of CPU: " + cpuInfo.getSysRate()
+ "\nUser Rate of CPU: " + cpuInfo.getUserRate()
+ "\nFree Rate of CPU: " + cpuInfo.getFreeRate());
return cpuInfoStr.toString();
}
private String diskInfotoString() {
StringBuffer diskInfoStr = new StringBuffer();
ArrayList<DiskInfo> diskInfos = this.getDiskInfos();
for (int i=0;i<diskInfos.size();i++) {
DiskInfo diskInfo = diskInfos.get(i);
if (i != diskInfos.size() - 1) {
diskInfoStr.append("Disk Desc: " + diskInfo.getDiskDesc()
+ "\nDisk Size: " + diskInfo.getDiskSize()
+ "\nDisk Free Size: " + diskInfo.getDiskFreeSize()
+ "\nDisk Used Size: " + diskInfo.getDiskUsedSize()
+ "\nDisk Used Percentage: " + diskInfo.getPercentUsed() + "%\n");
}else {
diskInfoStr.append("Whole Disk Desc: " + diskInfo.getDiskDesc()
+ "\nWhole Disk Size: " + diskInfo.getDiskSize()
+ "\nWhole Disk Free Size: " + diskInfo.getDiskFreeSize()
+ "\nWhole Disk Used Size: " + diskInfo.getDiskUsedSize()
+ "\nWhole Disk Used Percentage: " + diskInfo.getPercentUsed() + "%\n");
}
}
return diskInfoStr.toString();
}
}
snmp.physical包:snmp 协议采集数据核心
SnmpUtil.java :Snmp 协议基础类
package com.emc.snmp.physical;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import com.emc.snmp.comm.SnmpProperties;
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.Address;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
/**
* Created by Ouwei on 14-5-26.
* SNMP的基础类
*/
public class SnmpUtil {
public static final int DEFAULT_VERSION = SnmpConstants.version2c;
public static final String DEFAULT_PROTOCOL = "udp";
public static final int DEFAULT_PORT = 161;
public static final long DEFAULT_TIMEOUT = 3 * 1000L;
public static final int DEFAULT_RETRY = 3;
protected String ip;
protected String community;
protected static SnmpProperties props = SnmpProperties.loadProperties();
public CommunityTarget createDefault(String ip,String community) {
Address targetAddress = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip + "/" + DEFAULT_PORT);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(targetAddress);
target.setVersion(DEFAULT_VERSION);
target.setTimeout(DEFAULT_TIMEOUT);
target.setRetries(DEFAULT_RETRY);
return target;
}
public SnmpUtil(String ip,String community) {
this.ip = ip;
this.community = community;
}
@SuppressWarnings("rawtypes")
public String snmpGet(String oid) throws IOException {
CommunityTarget target = this.createDefault(ip, community);
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// get PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(oid)));// pcName
pdu.setType(PDU.GET);
return readResponse(snmp.send(pdu, target));
}
@SuppressWarnings("rawtypes")
public String readResponse(ResponseEvent respEvnt) {
// 解析Response
if (respEvnt != null && respEvnt.getResponse() != null) {
Vector recVBs = respEvnt.getResponse().getVariableBindings();
if (recVBs.size()>0) {
VariableBinding recVB = (VariableBinding) recVBs.elementAt(0);
return recVB.getVariable().toString();
}
}
return null;
}
@SuppressWarnings("rawtypes")
public ArrayList<String> snmpWalk(String oid) {
ArrayList<String> result = new ArrayList<String>();
TransportMapping transport = null;
Snmp snmp = null;
try {
CommunityTarget target = this.createDefault(ip, community);
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
PDU pdu = new PDU();
OID targetOID = new OID(oid);
pdu.add(new VariableBinding(targetOID));
boolean finished = false;
while (!finished) {
VariableBinding vb = null;
ResponseEvent respEvent = snmp.getNext(pdu, target);
PDU response = respEvent.getResponse();
if (null == response) {
finished = true;
break;
} else {
vb = response.get(0);
}
// check finish
finished = checkWalkFinished(targetOID, pdu, vb);
if (!finished) {
result.add(vb.getVariable().toString());
pdu.setRequestID(new Integer32(0));
pdu.set(0, vb);
} else {
//System.out.println("SNMP walk OID 结束.");
snmp.close();
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
//System.out.println("SNMP walk Exception: " + e);
} finally {
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex1) {
snmp = null;
}
}
}
return null;
}
public static boolean checkWalkFinished(OID targetOID, PDU pdu,
VariableBinding vb) {
boolean finished = false;
if (pdu.getErrorStatus() != 0) {
//System.out.println("[true] responsePDU.getErrorStatus() != 0 ");
//System.out.println(pdu.getErrorStatusText());
finished = true;
} else if (vb.getOid() == null) {
//System.out.println("[true] vb.getOid() == null");
finished = true;
} else if (vb.getOid().size() < targetOID.size()) {
//System.out.println("[true] vb.getOid().size() < targetOID.size()");
finished = true;
} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
//System.out.println("[true] targetOID.leftMostCompare() != 0");
finished = true;
} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
// System.out
// .println("[true] Null.isExceptionSyntax(vb.getVariable().getSyntax())");
finished = true;
} else if (vb.getOid().compareTo(targetOID) <= 0) {
// System.out.println("[true] Variable received is not "
// + "lexicographic successor of requested " + "one:");
// System.out.println(vb.toString() + " <= " + targetOID);
finished = true;
}
return finished;
}
}
SnmpBase.java:snmp 公用信息采集类
package com.emc.snmp.physical;
import com.emc.snmp.info.CpuInfo;
import com.emc.snmp.info.DiskInfo;
import com.emc.snmp.info.MemoryInfo;
import com.emc.snmp.info.SystemInfo;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by ouwei on 14-5-26.
* SNMP公用信息采集类 基本都是OID为1.3.6.1.2.1.25下的信息
*/
public class SnmpBase extends SnmpUtil {
public SnmpBase(String ip, String community) {
super(ip, community);
}
/*
* 基础的CPU信息采集,只能采集到核数与每个CPU的
*/
public CpuInfo getCpuInfo() throws Exception {
String browseDeviceIndexOID = props.getDeviceIndex();
String browseDeviceTypeOID = props.getDeviceType();
String browseDeviceInfoOID = props.getDeviceInfo();
String borwseDeviceLoadOID = props.getCpuCurrentLoadIndex();
String cpuOID = props.getCpuID();
ArrayList<String> rt = new ArrayList<String>();
ArrayList<CpuInfo> cpuInfos = new ArrayList<CpuInfo>();
int userRate = 0;
String cpuDesc = "";
try {
ArrayList<String> deviceIndex = snmpWalk(browseDeviceIndexOID);
// 因获取的CPU信息会有重覆,过滤掉一样的信息
boolean flag = true;
for (int i=0;i<deviceIndex.size();i++) {
String deviceType = snmpGet(browseDeviceTypeOID + "." + deviceIndex.get(i));
if (deviceType.equals(cpuOID)) {
String cpuInfo = snmpGet(browseDeviceInfoOID + "." + deviceIndex.get(i));
String loadCurrent = snmpGet(borwseDeviceLoadOID + "." + deviceIndex.get(i));
CpuInfo obj = new CpuInfo();
obj.setCpuDesc(cpuInfo);
obj.setUserRate(loadCurrent);
if (flag) {
int intelCpu = cpuInfo.indexOf("Intel");
int amdCpu = cpuInfo.indexOf("AMD");
if (intelCpu != -1) {
cpuDesc = cpuInfo.substring(intelCpu);
}else if (amdCpu != -1) {
cpuDesc = cpuInfo.substring(amdCpu);
}
flag = false;
}
userRate += Integer.parseInt(loadCurrent);
obj.setSysRate(loadCurrent);
obj.setFreeRate(Integer.toString(100 - Integer.parseInt(loadCurrent)));
cpuInfos.add(obj);
}
}
// 重新组合成CpuInfo类
// for(String str:rt) {
// CpuInfo obj = new CpuInfo();
// obj.setCpuDesc(str);
// cpuInfos.add(obj);
// }
int coreNum = this.getCpuCoreNum();
userRate = userRate/coreNum;
CpuInfo result = new CpuInfo();
result.setCpuDetailInfos(cpuInfos);
result.setCpuDesc(cpuDesc);
result.setSysRate(Integer.toString(userRate));
result.setFreeRate(Integer.toString(100 - userRate));
result.setCoreNum(coreNum);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private int getCpuCoreNum() {
String cpuCoreOID = props.getCpuCurrentLoadIndex();
ArrayList<String> result = snmpWalk(cpuCoreOID);
return result.size();
}
public String getMemorySize(){
String memorySizeOID = props.getMemoryTotalSize();
try {
NumberFormat nf = NumberFormat.getInstance();
nf.setRoundingMode(RoundingMode.HALF_UP);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
return nf.format(Double.parseDouble(snmpGet(memorySizeOID))/(1024*1024));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public MemoryInfo getMemoryInfo() throws Exception {
MemoryInfo memoryInfo = new MemoryInfo();
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
int index = this.getMemoryIndex();
double physicalSize = Double.parseDouble(snmpGet(props.getWindowDiskSize() + "." + index))*Double.parseDouble(snmpGet(props.getWindowDiskAmount() + "." + index))/(1024*1024*1024);
double physicalUsedSize = Double.parseDouble(snmpGet(props.getWindowDiskUsed() + "." + index))*Double.parseDouble(snmpGet(props.getWindowDiskAmount() + "." + index))/(1024*1024*1024);
memoryInfo.setMemorySize(nf.format(physicalSize));
memoryInfo.setMemoryUsedSize(nf.format(physicalUsedSize));
memoryInfo.setMemoryFreeSize(nf.format(physicalSize - physicalUsedSize));
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(0);
memoryInfo.setMemoryPercentage(nf.format(physicalUsedSize/physicalSize*100));
return memoryInfo;
}
private int getMemoryIndex() throws Exception {
ArrayList<String> diskIndexTable = this.snmpWalk(props
.getWindowDiskIndex());
String physicalMemoryID = props.getRamID();
int index = 0;
int i = 1;
for (String str : diskIndexTable) {
String diskType = this.snmpGet(props.getWindowDiskType() + "." + i);
if (diskType.equals(physicalMemoryID))
index = Integer.parseInt(str);
i++;
}
diskIndexTable = null;
return index;
}
public HashMap<String,String> getNetWorkInfo() {
return null;
}
public SystemInfo getSysInfo() throws Exception {
SystemInfo sysInfo = new SystemInfo();
sysInfo.setSysDesc(snmpGet(props.getSysDesc()));
sysInfo.setSysContact(snmpGet(props.getSysContact()));
sysInfo.setSysName(snmpGet(props.getSysName()));
sysInfo.setSysUpTime(snmpGet(props.getSysUptime()));
sysInfo.setSysLocation(snmpGet(props.getSysLocation()));
return sysInfo;
}
private ArrayList<String> getDiskIndex() throws Exception {
String hrStorageFixedDisk = props.getHrStorageFixedDisk();
//String hrStorageRamDisk = props.getHrStorageRamDisk();
//String hrStorageNetworkDisk = props.getHrStorageNetWorkDisk();
ArrayList<String> diskIndexTable = this.snmpWalk(props
.getWindowDiskIndex());
ArrayList<String> result = new ArrayList<String>();
for (String str : diskIndexTable) {
String diskType = this.snmpGet(props.getWindowDiskType() + "." + str);
if (diskType.equals(hrStorageFixedDisk))
result.add(str);
}
diskIndexTable = null;
return result;
}
/*
* 返回系统硬盘信息
* ArrayList<DiskInfo> 最后一个为硬盘的整个信息
* ArrayList value 硬盘信息 包括
*/
public ArrayList<DiskInfo> getDiskInfo() throws Exception {
ArrayList<String> index = this.getDiskIndex();
NumberFormat nf = NumberFormat.getInstance();
nf.setRoundingMode(RoundingMode.HALF_UP);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
double totalSize = 0; // 硬盘的整个大小
double totalUsedSize = 0; // 硬盘的使用空间
ArrayList<DiskInfo> result = new ArrayList<DiskInfo>();
for (int i=0;i<index.size();i++) {
DiskInfo obj = new DiskInfo();
obj.setDiskDesc(snmpGet(props.getWindowDiskDesc() + "." + index.get(i)));
double sSize = Double.parseDouble(snmpGet(props.getWindowDiskSize() + "." + index.get(i)))*Double.parseDouble(snmpGet(props.getWindowDiskAmount() + "." + index.get(i)))/(1024*1024*1024);
obj.setDiskSize(nf.format(sSize));
double usedSize = Double.parseDouble(snmpGet(props.getWindowDiskUsed() + "." + index.get(i)))*Double.parseDouble(snmpGet(props.getWindowDiskAmount() + "." + index.get(i)))/(1024*1024*1024);
obj.setDiskUsedSize(nf.format(usedSize));
obj.setDiskFreeSize(nf.format(sSize - usedSize));
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(0);
obj.setPercentUsed(Integer.parseInt(nf.format(usedSize/sSize*100)));
totalSize += sSize;
totalUsedSize += usedSize;
result.add(obj);
}
DiskInfo obj = new DiskInfo();
obj.setPercentUsed(Integer.parseInt(nf.format(totalUsedSize/totalSize * 100)));
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
obj.setDiskSize(nf.format(totalSize));
obj.setDiskUsedSize(nf.format(totalUsedSize));
obj.setDiskFreeSize(nf.format(totalSize - totalUsedSize));
result.add(obj);
return result;
}
public static void main(String[] args) {
SnmpBase snmp = new SnmpBase("192.168.0.21","public");
// SnmpBase snmp = new SnmpBase("115.28.24.101","qbdserver");
try {
// SystemInfo sysInfo = snmp.getSysInfo();
// System.out.println("System Desc: " + sysInfo.getSysDesc());
// System.out.println("System Name: " + sysInfo.getSysName());
// System.out.println("System Contact: " + sysInfo.getSysContact());
// System.out.println("System UpTime: " + sysInfo.getSysUpTime());
// System.out.println("System Location: " + sysInfo.getSysLocation());
// System.out.println("Memory Size: " + snmp.getMemorySize());
CpuInfo cpuInfo = snmp.getCpuInfo();
System.out.println("CPU Core Num: " + cpuInfo.getCoreNum());
System.out.println("CPU SysRate: " + cpuInfo.getSysRate());
System.out.println("CPU FreeRate: " + cpuInfo.getFreeRate());
System.out.println("CPU Desc: " + cpuInfo.getCpuDesc());
for(CpuInfo obj:cpuInfo.getCpuDetailInfos()) {
System.out.println("CPU Desc: " + obj.getCpuDesc());
System.out.println("CPU SysRate: " + obj.getSysRate());
System.out.println("CPU FreeRate: " + obj.getFreeRate());
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
SnmpEsxi:主要针对ESXI服务器的snmp 采集
package com.emc.snmp.physical;
import com.emc.snmp.info.MemoryInfo;
import com.emc.snmp.info.SystemInfo;
import java.text.NumberFormat;
import java.util.ArrayList;
/**
* Created by Administrator on 14-5-26.
*/
public class SnmpEsxi extends SnmpBase {
public SnmpEsxi(String ip, String community) {
super(ip, community);
}
public MemoryInfo getMemoryInfo() throws Exception {
MemoryInfo memoryInfo = new MemoryInfo();
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
int index = this.getMemoryIndex();
double physicalSize = Double.parseDouble(snmpGet(props.getWindowDiskSize() + "." + index))*Double.parseDouble(snmpGet(props.getWindowDiskAmount() + "." + index))/(1024*1024*1024);
double physicalUsedSize = Double.parseDouble(snmpGet(props.getWindowDiskUsed() + "." + index))*Double.parseDouble(snmpGet(props.getWindowDiskAmount() + "." + index))/(1024*1024*1024);
memoryInfo.setMemorySize(super.getMemorySize());
memoryInfo.setMemoryUsedSize(nf.format(physicalUsedSize));
memoryInfo.setMemoryFreeSize(nf.format(physicalSize - physicalUsedSize));
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(0);
memoryInfo.setMemoryPercentage(nf.format(physicalUsedSize/physicalSize*100));
return memoryInfo;
}
private int getMemoryIndex() throws Exception {
ArrayList<String> diskIndexTable = this.snmpWalk(props
.getWindowDiskIndex());
// String physicalMemoryID = props.getHrStorageRamDisk();
String physicalMemoryID = "1.3.6.1.2.1.25.2.1.20";
int index = 0;
int i = 1;
for (String str : diskIndexTable) {
String diskType = this.snmpGet(props.getWindowDiskType() + "." + i);
if (diskType.equals(physicalMemoryID))
index = Integer.parseInt(str);
i++;
}
diskIndexTable = null;
return index;
}
public SystemInfo getSysInfo() throws Exception {
SystemInfo sysInfo = super.getSysInfo();
sysInfo.setMemoryInfo(this.getMemoryInfo());
sysInfo.setDiskInfos(getDiskInfo());
sysInfo.setCpuInfo(getCpuInfo());
return sysInfo;
}
}
SnmpLinux.java:主要针对Linux 服务器snmp 采集
package com.emc.snmp.physical;
import com.emc.snmp.info.CpuInfo;
import com.emc.snmp.info.SystemInfo;
/**
* Created by Administrator on 14-5-26.
*/
public class SnmpLinux extends SnmpBase {
public SnmpLinux(String ip, String community) {
super(ip, community);
}
public CpuInfo getCpuInfo() throws Exception {
CpuInfo cpuInfo = super.getCpuInfo();
cpuInfo.setSysRate(snmpGet(props.getLinuxSysCPURate()));
cpuInfo.setUserRate(snmpGet(props.getLinuxUserCPURate()));
cpuInfo.setFreeRate(snmpGet(props.getLinuxFreeCPURate()));
return cpuInfo;
}
public SystemInfo getSysInfo() throws Exception {
SystemInfo sysInfo = super.getSysInfo();
sysInfo.setMemoryInfo(getMemoryInfo());
sysInfo.setDiskInfos(getDiskInfo());
sysInfo.setCpuInfo(getCpuInfo());
return sysInfo;
}
}
SnmpWindows.java:主要针对Windows 的snmp采集
package com.emc.snmp.physical;
import com.emc.snmp.info.SystemInfo;
/**
* Created by Administrator on 14-5-26.
*/
public class SnmpWindow extends SnmpBase {
public SnmpWindow(String ip, String community) {
super(ip, community);
}
public SystemInfo getSysInfo() throws Exception {
SystemInfo sysInfo = super.getSysInfo();
sysInfo.setMemoryInfo(getMemoryInfo());
sysInfo.setDiskInfos(getDiskInfo());
sysInfo.setCpuInfo(getCpuInfo());
return sysInfo;
}
}
snmp.util包:snmp 协议封装的采集工具类
SnmpType.java :主要是封装操作系统类型:
package com.emc.snmp.util;
/**
* Created by Ouwei on 14-5-27.
*/
public enum SnmpType {
WINDOWS("windows"),LINUX("linux"),ESXI("esxi");
private final String type;
private SnmpType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。