- 导入jsch依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
- 代码块
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
public class RemoteServerMonitor {
private static JSch jsch;
private static Session session;
/**
* 创建连接
* @param host
* @param port
* @param username
* @param password
* @throws JSchException
*/
private static void connect(String host, int port, String username, String password) throws JSchException {
if (jsch == null) {
jsch = new JSch();
session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
}
}
/**
* 关闭连接
*/
private static void disconnect() {
session.disconnect();
}
/**
* 运行命令获取结果
* @param command
* @return
* @throws JSchException
* @throws IOException
*/
private static String executeCommand(String command) throws JSchException, IOException {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.setInputStream(null);
channel.setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
StringBuilder output = new StringBuilder();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
output.append(new String(buffer, 0, bytesRead));
}
channel.disconnect();
return output.toString();
}
private static double parseCpuUsage(String commandOutput) {
String[] lines = commandOutput.split("\n");
String cpuLine = lines[0];
String[] cpuInfo = cpuLine.split(", ");
String cpuUsage = cpuInfo[0].split(": ")[1].trim().split(" ")[0];
return Double.parseDouble(cpuUsage);
}
/**
* 获取cpu使用率
* @return
*/
private static double getRemoteCpuUsage() {
try {
//获取cpu使用率命令
String command = "top -b -n 1 | grep Cpu";
String commandOutput = executeCommand(command);
double cpuUsage = parseCpuUsage(commandOutput);
return cpuUsage;
} catch (JSchException | IOException e) {
e.printStackTrace();
return -1;
}
}
public static void main(String[] args) {
try {
connect("clickhouse-virtual-machine", 22, "clickhouse", "root");
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
double cpu = getRemoteCpuUsage();
System.out.println("cpu:" + cpu );
}
} catch (JSchException | InterruptedException e) {
e.printStackTrace();
}
disconnect();
}
}