|
吾爱游客
发表于 2018-10-26 16:34
1.申 请 I D:slient
2.个人邮箱:blackjava@163.com
3.技术文章: 90后程序猿一枚,精通java略会一点scala和python等,简答写一个snmp客户端工具类 并获取一下服务器的cpu使用率吧。
开发工具:Eclipse
目标:通过安装在linux 7.3下的snmp server获取当前服务器的cpu使用率
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
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.GenericAddress;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SnmpData {
public static final int DEFAULT_VERSION = SnmpConstants.version2c;
public static final String DEFAULT_PROTOCOL = "udp";
public static final long DEFAULT_TIMEOUT = 3 * 1000L;
public static final int DEFAULT_RETRY = 3;
/**
* 创建对象communityTarget,用于返回target
*
* @param targetAddress
* @param community
* @param version
* @param timeOut
* @param retry
* @return CommunityTarget
*/
public synchronized static CommunityTarget createDefault(String ip, String community,int snmpPort) {
Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
+ "/" + snmpPort);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(community));
target.setAddress(address);
target.setVersion(DEFAULT_VERSION);
target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
target.setRetries(DEFAULT_RETRY);
return target;
}
/*根据OID,获取单条消息*/
public Variable snmpGet(String ip, String community, String oid,int snmpPort) {
Variable variable = null;
CommunityTarget target = createDefault(ip, community,snmpPort);
Snmp snmp = null;
try {
PDU pdu = new PDU();
// pdu.add(new VariableBinding(new OID(new int[]
// {1,3,6,1,2,1,1,2})));
pdu.add(new VariableBinding(new OID(oid)));
DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
pdu.setType(PDU.GET);
ResponseEvent respEvent = snmp.send(pdu, target);
PDU response = respEvent.getResponse();
if (response == null) {
System.out.println("response is null, request time out");
} else {
for (int i = 0; i < response.size(); i++) {
VariableBinding vb = response.get(i);
variable = vb.getVariable();
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("SNMP Get Exception:" + e);
} finally {
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex1) {
snmp = null;
}
}
}
return variable;
}
/*根据targetOID,获取树形数据*/
public Map<String,Variable> snmpWalk(String ip, String community, String targetOid,int snmpPort)
{
Map<String,Variable> map = new HashMap<String,Variable>();
CommunityTarget target = createDefault(ip, community,snmpPort);
TransportMapping transport = null;
Snmp snmp = null;
try {
transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
PDU pdu = new PDU();
OID targetOID = new OID(targetOid);
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;
map = null;
break;
} else {
vb = response.get(0);
}
// check finish
finished = checkWalkFinished(targetOID, pdu, vb);
if (!finished) {
Variable variable = vb.getVariable();
OID oid = vb.getOid();
map.put(oid.toString(), variable);
// Set up the variable binding for the next entry.
pdu.setRequestID(new Integer32(0));
pdu.set(0, vb);
} else {
snmp.close();
}
}
} 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 map;
}
private static boolean checkWalkFinished(OID targetOID, PDU pdu,
VariableBinding vb) {
boolean finished = false;
if (pdu.getErrorStatus() != 0) {
finished = true;
} else if (vb.getOid() == null) {
finished = true;
} else if (vb.getOid().size() < targetOID.size()) {
finished = true;
} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
finished = true;
} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
finished = true;
} else if (vb.getOid().compareTo(targetOID) <= 0) {
finished = true;
}
return finished;
}
public static void main(String[] args) {
String ip = "127.0.0.1";
SnmpData sd = new SnmpData();
Variable snmpGet = sd.snmpGet(ip , "public", "1.3.6.1.2.1.25.3.3.1.2", 161);
System.out.println(snmpGet.toString());
//判断snmp是否获取到信息 如果没有获取到则表示当前服务器 未启动snmp或者关机或者snmp信息填写错误
if(hrProcessorLoad == null ){
System.out.println(" ip:"+ip +" cpu信息采集异常");
continue ;
//如果获取到信息并且当前是异常线程则 将当前设备移回正常设备处理线程
}else{
//计算cpu利用率
Set<String> keySet = hrProcessorLoad.keySet();
long cpu = 0L;
for (String string : keySet) {
cpu += hrProcessorLoad.get(string).toLong();
}
double cpuUsageRate = 1.0 * cpu / (keySet.size() * 100) * 100 ;
System.out.println(" ip:"+ip +" 当前cpu使用率是:"+cpuUsageRate +"%");
}
}}
|
-
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|