package com.sinosoft.common.utils;
import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author zyq
* @Date 2020/5/29
* @Description: 获取远程linux服务器 cpu、磁盘、内存
*/
public class LinuxStateForShell {
public static final String CPU_MEM_SHELL = "top -b -n 1";
public static final String FILES_SHELL = "df -hl";
public static final String[] COMMANDS = {CPU_MEM_SHELL, FILES_SHELL};
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static Session session;
/**
* 连接到指定的HOST
*
* @return isConnect
* @throws JSchException JSchException
*/
private static boolean connect(String user, String passwd, String host) {
JSch jsch = new JSch();
try {
session = jsch.getSession(user, host, 22);
session.setPassword(passwd);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
} catch (JSchException e) {
e.printStackTrace();
System.out.println("connect error !");
return false;
}
return true;
}
/**
* 远程连接Linux 服务器 执行相关的命令
*
* @param commands 执行的脚本
* @param user 远程连接的用户名
* @param passwd 远程连接的密码
* @param host 远程连接的主机IP
* @return 最终命令返回信息
*/
public static Map runDistanceShell(String[] commands, String user, String passwd, String host) {
if (!connect(user, passwd, host)) {
return null;
}
Map map = new HashMap<>();
StringBuilder stringBuffer;
BufferedReader reader = null;
Channel channel = null;
try {
for (String command : commands) {
stringBuffer = new StringBuilder();
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
InputStream in = channel.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String buf;
while ((buf = reader.readLine()) != null) {
//舍弃PID 进程信息
if (buf.contains("PID")) {
break;
}
stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
}
//每个命令存储自己返回数据-用于后续对返回数据进行处理
map.put(command, stringBuffer.toString());
}
} catch (IOException | JSchException e) {
e.printStackTrace();
} finally
xshell 获取远程linux服务器 cpu、磁盘、内存
最新推荐文章于 2024-03-23 09:17:14 发布