<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
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;
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;
}
public static Map<String, String> runDistanceShell(String[] commands, String user, String passwd, String host) {
if (!connect(user, passwd, host)) {
return null;
}
Map<String, String> 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) {
if (buf.contains("PID")) {
break;
}
stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
}
map.put(command, stringBuffer.toString());
}
} catch (IOException | JSchException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (channel != null) {
channel.disconnect();
}
session.disconnect();
}
return map;
}
public static Map<String, String> runLocalShell(String[] commands) {
Runtime runtime = Runtime.getRuntime();
Map<String, String> map = new HashMap<>();
StringBuilder stringBuffer;
BufferedReader reader;
Process process;
for (String command : commands) {
stringBuffer = new StringBuilder();
try {
process = runtime.exec(command);
InputStream inputStream = process.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
String buf;
while ((buf = reader.readLine()) != null) {
if (buf.contains("PID")) {
break;
}
stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
map.put(command, stringBuffer.toString());
}
return map;
}
private static String disposeResultMessage(Map<String, String> result) {
StringBuilder buffer = new StringBuilder();
for (String command : COMMANDS) {
String commandResult = result.get(command);
if (null == commandResult) continue;
if (command.equals(CPU_MEM_SHELL)) {
String[] strings = commandResult.split(LINE_SEPARATOR);
for (String line : strings) {
line = line.toUpperCase();
if (line.startsWith("CPU(S):")) {
String cpuStr = "CPU 用户使用占有率:";
try {
cpuStr += line.split(":")[1].split(",")[0].replace("US", "");
} catch (Exception e) {
e.printStackTrace();
cpuStr += "计算过程出错";
}
buffer.append(cpuStr).append(LINE_SEPARATOR);
} else if (line.startsWith("MEM")) {
String memStr = "内存使用情况:";
try {
memStr += line.split(":")[1]
.replace("TOTAL", "总计")
.replace("USED", "已使用")
.replace("FREE", "空闲")
.replace("BUFFERS", "缓存");
} catch (Exception e) {
e.printStackTrace();
memStr += "计算过程出错";
buffer.append(memStr).append(LINE_SEPARATOR);
continue;
}
buffer.append(memStr).append(LINE_SEPARATOR);
}
}
} else if (command.equals(FILES_SHELL)) {
buffer.append("系统磁盘状态:");
try {
buffer.append(disposeFilesSystem(commandResult)).append(LINE_SEPARATOR);
} catch (Exception e) {
e.printStackTrace();
buffer.append("计算过程出错").append(LINE_SEPARATOR);
}
}
}
return buffer.toString();
}
private static String disposeFilesSystem(String commandResult) {
String[] strings = commandResult.split(LINE_SEPARATOR);
int size = 0;
int used = 0;
for (int i = 0; i < strings.length - 1; i++) {
if (i == 0) continue;
int temp = 0;
for (String s : strings[i].split("\\b")) {
if (temp == 0) {
temp++;
continue;
}
if (!s.trim().isEmpty()) {
if (temp == 1) {
size += disposeUnit(s);
temp++;
} else {
used += disposeUnit(s);
temp = 0;
}
}
}
}
return new StringBuilder().append("大小 ").append(size).append("G , 已使用").append(used).append("G ,空闲")
.append(size - used).append("G").toString();
}
private static int disposeUnit(String s) {
try {
s = s.toUpperCase();
String lastIndex = s.substring(s.length() - 1);
String num = s.substring(0, s.length() - 1);
int parseInt = Integer.parseInt(num);
if (lastIndex.equals("G")) {
return parseInt;
} else if (lastIndex.equals("T")) {
return parseInt * 1024;
} else if (lastIndex.equals("M")) {
return parseInt / 1024;
} else if (lastIndex.equals("K") || lastIndex.equals("KB")) {
return parseInt / (1024 * 1024);
}
} catch (NumberFormatException e) {
e.printStackTrace();
return 0;
}
return 0;
}
public static void main(String[] args) {
System.out.println(disposeResultMessage(runLocalShell(COMMANDS)));
}
}