Linux Java 获取CPU使用率,内存使用率,磁盘IO,网络带宽使用率等等

<pre name="code" class="java"> /**
* 获取带宽上传下载速度
* @return
*/
public String getNetWorkSpeed() {
boolean result = false;
String detailInfo = "";
DecimalFormat df = new DecimalFormat("0.00");
String dl = "";
String ul = "";
System.out.println("开始收集网络带宽使用率");
Process pro1,pro2;
Runtime r = Runtime.getRuntime();
try {
String command = "cat /proc/net/dev";
//第一次采集流量数据
long startTime = System.currentTimeMillis();
pro1 = r.exec(command);
BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream()));
String line = null;
long inSize1 = 0, outSize1 = 0;
while((line=in1.readLine()) != null){
line = line.trim();
if(line.startsWith("eth0")){
System.out.println(line);
String[] temp = line.split("\\s+");
inSize1 = Long.parseLong(temp[1]); //Receive bytes,单位为Byte
outSize1 = Long.parseLong(temp[9]); //Transmit bytes,单位为Byte
break;
}
}
in1.close();
pro1.destroy();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("NetUsage休眠时发生InterruptedException. " + e.getMessage());
System.out.println(sw.toString());
}
//第二次采集流量数据
long endTime = System.currentTimeMillis();
pro2 = r.exec(command);
BufferedReader in2 = new BufferedReader(new InputStreamReader(pro2.getInputStream()));
long inSize2 = 0 ,outSize2 = 0;
while((line=in2.readLine()) != null){
line = line.trim();
if(line.startsWith("eth0")){
System.out.println(line);
String[] temp = line.split("\\s+");
inSize2 = Long.parseLong(temp[1]);
outSize2 = Long.parseLong(temp[9]);
break;
}
}

//cal dl speed
float interval = (float)(endTime - startTime)/1000;
float currentDlSpeed = (float) ((float)(inSize2 - inSize1)/1024/interval);
float currentUlSpeed = (float) ((float)(outSize2 - outSize1)/1024/interval);

if((float)(currentDlSpeed/1024) >= 1){
currentDlSpeed = (float)(currentDlSpeed/1024);
dl = df.format(currentDlSpeed) + "Mb/s";
}else{
dl = df.format(currentDlSpeed) + "Kb/s";
}

if((float)(currentUlSpeed/1024) >= 1){
currentUlSpeed = (float)(currentUlSpeed/1024);
ul = df.format(currentUlSpeed) + "Mb/s";
}else{
ul = df.format(currentUlSpeed) + "Kb/s";
}
result = true;
in2.close();
pro2.destroy();
} catch (Exception e) {
e.printStackTrace();
detailInfo = e.getMessage();
}
return "{\"result\":\""+result+"\",\"detailInfo\":\""+detailInfo+"\",\"dl\":\""+dl+"\",\"ul\":\""+ul+"\"}";
}

 

/**
* 功能:内存使用率
* */
public float memoryUsage() {
Map<String, Object> map = new HashMap<String, Object>();
InputStreamReader inputs = null;
BufferedReader buffer = null;
try {
inputs = new InputStreamReader(new FileInputStream("/proc/meminfo"));
buffer = new BufferedReader(inputs);
String line = "";
while (true) {
line = buffer.readLine();
if (line == null)
break;
int beginIndex = 0;
int endIndex = line.indexOf(":");
if (endIndex != -1) {
String key = line.substring(beginIndex, endIndex);
beginIndex = endIndex + 1;
endIndex = line.length();
String memory = line.substring(beginIndex, endIndex);
String value = memory.replace("kB", "").trim();
map.put(key, value);
}
}

long memTotal = Long.parseLong(map.get("MemTotal").toString());
long memFree = Long.parseLong(map.get("MemFree").toString());
long memused = memTotal - memFree;
long buffers = Long.parseLong(map.get("Buffers").toString());
long cached = Long.parseLong(map.get("Cached").toString());
float usage = (float) (memused - buffers - cached) / memTotal;
return usage;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
inputs.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return 0;
}

 

 

/**
* 获取分区的使用占用率
* @param path
* @return
*/
public float getPatitionUsage(String path){
File f = new File(path);
long total = f.getTotalSpace();
long free = f.getFreeSpace();
long used = total - free;
float usage = (float)used/total;
return usage;
}

 

/**
* 获取磁盘IO使用率
* @return
*/
public float getHdIOpPercent() {
System.out.println("开始收集磁盘IO使用率");
float ioUsage = 0.0f;
Process pro = null;
Runtime r = Runtime.getRuntime();
try {
String command = "iostat -d -x";
pro = r.exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line = null;
int count = 0;
while((line=in.readLine()) != null){
if(++count >= 4){
// System.out.println(line);
String[] temp = line.split("\\s+");
if(temp.length > 1){
float util = Float.parseFloat(temp[temp.length-1]);
ioUsage = (ioUsage>util)?ioUsage:util;
}
}
}
if(ioUsage > 0){
System.out.println("本节点磁盘IO使用率为: " + ioUsage);
ioUsage /= 100;
}
in.close();
pro.destroy();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("IoUsage发生InstantiationException. " + e.getMessage());
System.out.println(sw.toString());
}
return ioUsage;
}

 

/**
* 获取带宽使使用率
* @return
*/
public float get() {
float TotalBandwidth = 1000;
System.out.println("开始收集网络带宽使用率");
float netUsage = 0.0f;
Process pro1,pro2;
Runtime r = Runtime.getRuntime();
try {
String command = "cat /proc/net/dev";
//第一次采集流量数据
long startTime = System.currentTimeMillis();
pro1 = r.exec(command);
BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream()));
String line = null;
long inSize1 = 0, outSize1 = 0;
while((line=in1.readLine()) != null){
line = line.trim();
if(line.startsWith("eth0")){
System.out.println(line);
String[] temp = line.split("\\s+");
inSize1 = Long.parseLong(temp[1].substring(5)); //Receive bytes,单位为Byte
outSize1 = Long.parseLong(temp[9]); //Transmit bytes,单位为Byte
break;
}
}
in1.close();
pro1.destroy();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("NetUsage休眠时发生InterruptedException. " + e.getMessage());
System.out.println(sw.toString());
}
//第二次采集流量数据
long endTime = System.currentTimeMillis();
pro2 = r.exec(command);
BufferedReader in2 = new BufferedReader(new InputStreamReader(pro2.getInputStream()));
long inSize2 = 0 ,outSize2 = 0;
while((line=in2.readLine()) != null){
line = line.trim();
if(line.startsWith("eth0")){
System.out.println(line);
String[] temp = line.split("\\s+");
inSize2 = Long.parseLong(temp[1].substring(5));
outSize2 = Long.parseLong(temp[9]);
break;
}
}
if(inSize1 != 0 && outSize1 !=0 && inSize2 != 0 && outSize2 !=0){
float interval = (float)(endTime - startTime)/1000;
//网口传输速度,单位为bps
float curRate = (float)(inSize2 - inSize1 + outSize2 - outSize1)*8/(1000000*interval);
netUsage = curRate/TotalBandwidth;
System.out.println("本节点网口速度为: " + curRate + "Mbps");
System.out.println("本节点网络带宽使用率为: " + netUsage);
}
in2.close();
pro2.destroy();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("NetUsage发生InstantiationException. " + e.getMessage());
System.out.println(sw.toString());
}
return netUsage;
}

 

 

/**
* 功能:可用磁盘
* */
public static int disk() {
try {
long total = FileSystemUtils.freeSpaceKb("/");
double disk = (double) total / 1024 / 1024;
return (int) disk;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}

/**
* 功能:获取Linux系统cpu使用率
* */
public static String cpuUsage() {
try {
Map<?, ?> map1 = SysStatusInfo.cpuinfo();
Thread.sleep(1 * 1000);
Map<?, ?> map2 = SysStatusInfo.cpuinfo();

long user1 = Long.parseLong(map1.get("user").toString());
long nice1 = Long.parseLong(map1.get("nice").toString());
long system1 = Long.parseLong(map1.get("system").toString());
long idle1 = Long.parseLong(map1.get("idle").toString());

long user2 = Long.parseLong(map2.get("user").toString());
long nice2 = Long.parseLong(map2.get("nice").toString());
long system2 = Long.parseLong(map2.get("system").toString());
long idle2 = Long.parseLong(map2.get("idle").toString());

long total1 = user1 + system1 + nice1;
long total2 = user2 + system2 + nice2;
float total = total2 - total1;

long totalIdle1 = user1 + nice1 + system1 + idle1;
long totalIdle2 = user2 + nice2 + system2 + idle2;
float totalidle = totalIdle2 - totalIdle1;

DecimalFormat df = new DecimalFormat(".0");
float cpusage = (float)(total / totalidle) * 100;
String value = df.format(cpusage);
return value;
} catch (InterruptedException e) {
e.printStackTrace();
}
return "0";
}

/**
* 功能:CPU使用信息
* */
public static Map<?, ?> cpuinfo() {
InputStreamReader inputs = null;
BufferedReader buffer = null;
Map<String, Object> map = new HashMap<String, Object>();
try {
inputs = new InputStreamReader(new FileInputStream("/proc/stat"));
buffer = new BufferedReader(inputs);
String line = "";
while (true) {
line = buffer.readLine();
if (line == null) {
break;
}
if (line.startsWith("cpu")) {
StringTokenizer tokenizer = new StringTokenizer(line);
List<String> temp = new ArrayList<String>();
while (tokenizer.hasMoreElements()) {
String value = tokenizer.nextToken();
temp.add(value);
}
map.put("user", temp.get(1));
map.put("nice", temp.get(2));
map.put("system", temp.get(3));
map.put("idle", temp.get(4));
map.put("iowait", temp.get(5));
map.put("irq", temp.get(6));
map.put("softirq", temp.get(7));
map.put("stealstolen", temp.get(8));
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
inputs.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return map;
}

 

int kb = 1024;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 操作系统
String osName = System.getProperty("os.name");
// 总的物理内存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
// 剩余的物理内存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// 已使用的物理内存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb .getFreePhysicalMemorySize()) / kb;

 

</pre><pre name="code" class="java">/**
* 获取CPU使用率
* @return
*/
public float getCpuUsage() {
System.out.println("开始收集cpu使用率");
float cpuUsage = 0;
Process pro1,pro2;
Runtime r = Runtime.getRuntime();
try {
String command = "cat /proc/stat";
//第一次采集CPU时间
long startTime = System.currentTimeMillis();
pro1 = r.exec(command);
BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream()));
String line = null;
long idleCpuTime1 = 0, totalCpuTime1 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
while((line=in1.readLine()) != null){
if(line.startsWith("cpu")){
line = line.trim();
System.out.println(line);
String[] temp = line.split("\\s+");
idleCpuTime1 = Long.parseLong(temp[4]);
for(String s : temp){
if(!s.equals("cpu")){
totalCpuTime1 += Long.parseLong(s);
}
}
System.out.println("IdleCpuTime: " + idleCpuTime1 + ", " + "TotalCpuTime" + totalCpuTime1);
break;
}
}
in1.close();
pro1.destroy();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("CpuUsage休眠时发生InterruptedException. " + e.getMessage());
System.out.println(sw.toString());
}
//第二次采集CPU时间
long endTime = System.currentTimeMillis();
pro2 = r.exec(command);
BufferedReader in2 = new BufferedReader(new InputStreamReader(pro2.getInputStream()));
long idleCpuTime2 = 0, totalCpuTime2 = 0; //分别为系统启动后空闲的CPU时间和总的CPU时间
while((line=in2.readLine()) != null){
if(line.startsWith("cpu")){
line = line.trim();
System.out.println(line);
String[] temp = line.split("\\s+");
idleCpuTime2 = Long.parseLong(temp[4]);
for(String s : temp){
if(!s.equals("cpu")){
totalCpuTime2 += Long.parseLong(s);
}
}
System.out.println("IdleCpuTime: " + idleCpuTime2 + ", " + "TotalCpuTime" + totalCpuTime2);
break;
}
}
if(idleCpuTime1 != 0 && totalCpuTime1 !=0 && idleCpuTime2 != 0 && totalCpuTime2 !=0){
cpuUsage = 1 - (float)(idleCpuTime2 - idleCpuTime1)/(float)(totalCpuTime2 - totalCpuTime1);
System.out.println("本节点CPU使用率为: " + cpuUsage);
}
in2.close();
pro2.destroy();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("CpuUsage发生InstantiationException. " + e.getMessage());
System.out.println(sw.toString());
}
return cpuUsage;
}

 

获取MAC

 Windows

/**
* 获取MAC地址
*
* @return
*/
public String getMac() {
NetworkInterface byInetAddress;
try {
InetAddress localHost = InetAddress.getLocalHost();
byInetAddress = NetworkInterface.getByInetAddress(localHost);
byte[] hardwareAddress = byInetAddress.getHardwareAddress();
return getMacFromBytes(hardwareAddress);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(getLocalTime()+"获取mac地址失败:" + e.getMessage());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(getLocalTime()+"获取mac地址失败:" + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(getLocalTime()+"获取mac地址失败:" + e.getMessage());
}
return null;
}

public String getMacFromBytes(byte[] bytes) {
StringBuffer mac = new StringBuffer();
byte currentByte;
boolean first = false;
for (byte b : bytes) {
if (first) {
mac.append("-");
}
currentByte = (byte) ((b & 240) >> 4);
mac.append(Integer.toHexString(currentByte));
currentByte = (byte) (b & 15);
mac.append(Integer.toHexString(currentByte));
first = true;
}
return mac.toString().toLowerCase();
}

 

Linux

 

/**
* 获取MAC
*
* @return
*/
public String getMac() {
String result = "";
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface network = networkInterfaces.nextElement();
System.out.println("network : " + network);
byte[] mac = network.getHardwareAddress();
if (mac == null) {
System.out.println("null mac");
} else {
System.out.print("MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i],
(i < mac.length - 1) ? ":" : ""));
}
result = sb.toString();
System.out.println(sb.toString());
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return result;
}

 

 

 

 

posted @ 2020-06-11 13:42  dfj_12345  阅读(1022)  评论(0编辑  收藏  举报