package com.learn.service; 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; /** * 遠程調用Linux shell 命令 * @author yuyihao 2019.10.12 */ public class LinuxStateForShell { public static final String CPU_MEM_SHELL = "top -b -n 1"; // liunx 命令用戶獲取系統信息 public static final String FILES_SHELL = "df -hl"; // 查看磁盤佔用情況 public static final String[] COMMANDS = {CPU_MEM_SHELL, FILES_SHELL}; // 命令數組 /** * 在java中存在一些轉義字符,比如"\n"爲換行符, JDK自帶的一些操作符 System.getProperty("line.separator"); * 這也是換行符,功能和"\n"是一致的,用此方法能區分 Windows和Linux環境的換行。 * 開發中與不是同一個環境,可以用 System.getProperty("line.separator"); 來控制換行 */ 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<String, String> runDistanceShell(String[] commands, String user, String passwd, String host) throws IOException { 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) { //捨棄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 { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } if (channel != null) { channel.disconnect(); } session.disconnect(); } return map; } /** * 處理 shell 返回的信息 * 具體處理過程以服務器返回數據格式爲準 * 不同的Linux 版本返回信息格式不同 * @param result shell 返回的信息 * @return 最終處理後的信息 */ 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();//轉大寫處理 //處理CPU Cpu(s): 10.8%us, 0.9%sy, 0.0%ni, 87.6%id, 0.7%wa, 0.0%hi, 0.0%si, 0.0%st 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); //處理內存 Mem: 66100704k total, 65323404k used, 777300k free, 89940k buffers } 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(); } //處理系統磁盤狀態 /** * @param commandResult 處理系統磁盤狀態shell執行結果 * @return 處理後的結果 */ /** * 最終處理的結果 * CPU 用戶使用佔有率: 0.2% * 內存使用情況: 1020344K 總計, 160248K 已使用, 860096K 空閒, 14176K 緩存 * 系統磁盤狀態:大小 7.66G , 已使用2.93G ,空閒4.73G */ private static String disposeFilesSystem(String commandResult) { String[] strings = commandResult.split(LINE_SEPARATOR); // final String PATTERN_TEMPLATE = "([a-zA-Z0-9%_/]*)\\s"; Double size = 0d; Double used = 0d; for (int i = 1; i < strings.length; i++) {//第一行 標題不需要 String[] row = strings[i].split("\\s+"); size += disposeUnit(row[1]); // 第二列 size used += disposeUnit(row[2]); // 第三列 used } return new StringBuilder().append("大小 ").append(Math.round(size * 100)/100d).append("G , 已使用").append(Math.round(used * 100)/100d).append("G ,空閒") .append(Math.round((size - used) * 100)/100d).append("G").toString(); } /** * 處理單位轉換 * K/KB/M/T 最終轉換爲G 處理 * @param s 帶單位的數據字符串 * @return 以G 爲單位處理後的數值 */ private static Double disposeUnit(String s) { try { s = s.toUpperCase(); String lastIndex = s.substring(s.length() - 1); String num = s.substring(0, s.length() - 1); Double parseInt = Double.parseDouble(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 0d; } return 0d; } public static void main(String[] args) throws IOException { Map<String, String> result = runDistanceShell(COMMANDS, "root", "root123", "192.168.56.101"); System.out.println(disposeResultMessage(result)); } } 重要的事情說三遍! 不同版本的Linux 執行的命令返回的數據是不一樣的 具體問題還得具體分析
本例使用的Liunx版本:
top -b -n 1 執行後的數據
df -hl 執行後的數據