【Java】+获取Linux服务器的CPU、内存使⽤率
package com.ool;
hz.ssh2.Connection;
hz.ssh2.Session;
hz.ssh2.StreamGobbler;
import com.ool.file.ZgxFileUtil;
import org.apachemons.lang3.tuple.Pair;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* @author
* @version 1.0
* @time 2019/7/15 20:28
* <p>
* 类功能说明:
* 1、连接服务器
* 2、执⾏Linux⽇志查询命令,返回查询后的⽇志字符串(以⾏为单位)
*/
public class LogAuto {
private static Logger log;
private Session ssh;
private String hostName;
private String userName;
private String password;
private int port;
/**
* 连接服务器
*
* @param hostname 服务器IP
* @param port 端⼝
* @param username 账号
* @param password 密码
*/
public LogAuto(String hostname, int port, String username, String password) {
this.hostName = hostname;
this.port = port;
this.userName = username;
this.password = password;
this.log = Loger(LogAuto.class);
}
/**
* 通过Linux命令查询⽇志内容
*
* @param command Linux⽇志查询命令
* @return返回根据命令查出的⽇志内容
*/
public List<String> execCom(String command) {
Connection conn = new Connection(this.hostName, this.port);
createConnection(conn);
List<String> logContent = new ArrayList<String>();
try {
} catch (IOException e) {
e.printStackTrace();
}
//将Terminal屏幕上的⽂字全部打印出来
InputStream is = new Stdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is));
while (true) {
String line = null;
try {
line = adLine();
} catch (IOException e) {
e.printStackTrace();
}
if (line == null) {
break;
}
// System.out.println(line);
logContent.add(line);
}
return logContent;
}
private void createConnection(Connection connection) {
//创建连接
try {
} catch (IOException e) {
e.printStackTrace();
}
try {
connection.authenticateWithPassword(this.userName, this.password);
} catch (IOException e) {
e.printStackTrace();
}
//创建与服务器的会话节点
try {
setSsh(connection.openSession());
} catch (IOException e) {
e.printStackTrace();
}
}
private void setSsh(Session ssh) {
this.ssh = ssh;
}
private Session getSsh() {
return ssh;
}
/**
* 功能:获取指定服务器在当前时间的内存使⽤率
*
* @param logAuto
* @return返回使⽤率(百分⽐)
*/
public static double getMemoryRate(LogAuto logAuto) {
String shell = String.format("%s", "free"); // 多个命令⽤“;”隔开
List<String> listResult = Com(shell);
// 打印shell命令执⾏后的结果
for (int i = 0; i < listResult.size(); i++) {
System.out.(i));
}
// 提取内存数据(第⼆⾏)
List<String> mem = ZgxStringUtil.(1), " ");
Integer usedMemory = Integer.(2));
Integer allMemory = Integer.(1));
log.info(String.format("usedMemory=%s;allMemory=%s", usedMemory, allMemory));
// 计算内存使⽤率(已使⽤内存/总内存)
double f1 = new BigDecimal((float) usedMemory / allMemory).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100; log.info(String.format("内存使⽤率=%s%s", f1, "%"));
return f1;
}
private static Pair getCpuData(LogAuto logAuto) {
String shell = String.format("%s", "cat /proc/stat"); // 多个命令⽤“;”隔开
List<String> listResult = Com(shell);
// 打印shell命令执⾏后的结果
for (int i = 0; i < listResult.size(); i++) {
System.out.(i));
log4j与log4j2}
// 提取CPU数据(第⼀⾏)
List<String> mem = ZgxStringUtil.(0), " ");
Long allTime1 = 0L;
for (int i = 0; i < mem.size(); i++) {
allTime1 += Long.(i));
}
System.out.println(String.format("CPU使⽤总时间=%s;idle=%s", allTime1, (3)));
return Pair.of(allTime1, (3));
}
/**
* 功能:获取指定服务器在当前时间的CPU使⽤率
*
* @param logAuto
* @return返回使⽤率(百分⽐)
*/
public static double getCpuRate(LogAuto logAuto) {
Pair cpuData1 = getCpuData(logAuto);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Pair cpuData2 = getCpuData(logAuto);
// step1 计算两次的cpu总时间
Long allTime = Long.Left().toString()) - Long.Left().toString());
// step2 计算两次的cpu剩余时间
Long idle = Long.Right().toString()) - Long.Right().toString());
// step3 计算两次的cpu使⽤时间
Long used = allTime - idle;
// step4 计算cpu使⽤率(cpu使⽤率 = 使⽤时间 / 总时间 * 100%)
double f1 = new BigDecimal((float) used / allTime).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100; log.info(String.format("CPU使⽤率=%s%s", f1, "%"));
return f1;
}
public static void main(String[] args) {
LogAuto logAuto = new LogAuto("服务器IP", 端⼝号, "账号", "密码");
getMemoryRate(logAuto);
getCpuRate(logAuto);
String[] header = {"时间,CPU使⽤率,内存使⽤率"};
List<String[]> content = new ArrayList<>();
// 每分钟获取⼀次服务器CPU、内存使⽤率(获取30次)
for (int i = 0; i < 30; i++) {
String[] data = {NowDate("yyyy-MM-dd HH:mm:ss")
, String.valueOf(getCpuRate(logAuto))
, String.valueOf(getMemoryRate(logAuto))};
content.add(data);
ZgxFileUtil.writeCsv("服务器性能数据.csv", header, content);
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论