依賴
<dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency>
ZgxFileUtil工具

package com.file; import com.ZgxLoggerUtil; import com.csvreader.CsvReader; import com.csvreader.CsvWriter; import org.apache.log4j.Logger; import javax.swing.*; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** * @author Jarvis * @version 1.0 * @time 2019/12/20 9:35 */ public class ZgxFileUtil { private static Logger log = ZgxLoggerUtil.getLogger(ZgxFileUtil.class); /** * 功能:將數據寫入csv文件中 * * @param filePath 文件路徑 * @param header 文件頭 * @param contents 文件內容 * @return */ static public boolean writeCsv(String filePath, String[] header, List<String[]> contents) { CsvWriter csvWriter = new CsvWriter(filePath, ',', Charset.forName("GBK")); // 寫入文件頭 if (header != null) { try { csvWriter.writeRecord(header); } catch (IOException e) { e.printStackTrace(); } } // 寫入文件行 for (int i = 0; i < contents.size(); i++) { try { csvWriter.writeRecord(contents.get(i)); } catch (IOException e) { e.printStackTrace(); } } csvWriter.close(); return true; } static public boolean writeCsv(String filePath, String[] header, List<String[]> contents, JProgressBar jProgressBar, List<String> fileType) { List<CsvWriter> csvWriterList = new ArrayList<>(); for (int i = 0; i < fileType.size(); i++) { csvWriterList.add(new CsvWriter(String.format("%s.%s", filePath, fileType.get(i)), ',', Charset.forName("GBK"))); } // 寫入文件頭 if (header != null) { try { for (int i = 0; i < csvWriterList.size(); i++) { csvWriterList.get(i).writeRecord(header); } } catch (IOException e) { e.printStackTrace(); } } // 寫入文件行 try { for (int i = 0; i < contents.size(); i++) { for (int j = 0; j < csvWriterList.size(); j++) { csvWriterList.get(j).writeRecord(contents.get(i)); System.out.println(String.format("寫入“%s”文件 第%s行", csvWriterList.get(j), i + 1)); } jProgressBar.setValue(i + 1); System.out.println(String.format("總:%s 最小:%s 最大:%s 當前:%s", contents.size(), jProgressBar.getMinimum(), jProgressBar.getMaximum(), i)); } for (int i = 0; i < csvWriterList.size(); i++) { csvWriterList.get(i).close(); } } catch (IOException e) { e.printStackTrace(); } return true; } /** * 功能:讀取CSV文件 * * @param readHeaders 是否要讀文件頭 * @param filePath 文件路徑 * @return 返回讀取的數據 */ static public List<String[]> readCsv(boolean readHeaders, String filePath) { List<String[]> contentHangs = new ArrayList<>(); try { CsvReader csvReader = new CsvReader(filePath, ',', Charset.forName("GBK")); if (!readHeaders) { csvReader.readHeaders(); } while (csvReader.readRecord()) { contentHangs.add(csvReader.getValues()); } csvReader.close(); } catch (IOException e) { e.printStackTrace(); } int hang = 0; int lie = 0; log.info(String.format("第%s行第%s列的數據=%s", hang, lie, contentHangs.get(hang)[lie])); return contentHangs; } /** * 功能:數據清洗(讀取一個舊文件的數據 清洗預期的數據后 再寫入到一個新的文件中) * 備注:清洗邏輯需變更 * * @param oldFilePath 原文件路徑 * @param newFilePath 清洗后的新文件路徑 */ static public void readAndWriteCsv(String oldFilePath, String newFilePath) { /** 【清洗原理】從idb上導出的數據 有雙引號引起來的 所以要清洗下數據 取雙引號中間的數據*/ // step1 讀取文件 清洗數據 List<String[]> read = readCsv(false, oldFilePath); List<String[]> newData = new ArrayList<>(); for (int i = 0; i < read.size(); i++) { String[] substring = {read.get(i)[0].substring(0, read.get(i)[0].length())}; newData.add(substring); } // step2 將清洗后的數據寫入文件 writeCsv(newFilePath, null, newData); } }
代碼
package com.alipay.ipay.gn.commontool; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import com.alipay.ipay.gn.commontool.file.ZgxFileUtil; import org.apache.commons.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 = ZgxLoggerUtil.getLoger(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 { ssh.execCommand(command); } catch (IOException e) { e.printStackTrace(); } //將Terminal屏幕上的文字全部打印出來 InputStream is = new StreamGobbler(ssh.getStdout()); BufferedReader brs = new BufferedReader(new InputStreamReader(is)); while (true) { String line = null; try { line = brs.readLine(); } catch (IOException e) { e.printStackTrace(); } if (line == null) { break; } // System.out.println(line); logContent.add(line); } return logContent; } private void createConnection(Connection connection) { //創建連接 try { connection.connect(); } 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 = logAuto.execCom(shell); // 打印shell命令執行后的結果 for (int i = 0; i < listResult.size(); i++) { System.out.println(listResult.get(i)); } // 提取內存數據(第二行) List<String> mem = ZgxStringUtil.splitString(listResult.get(1), " "); Integer usedMemory = Integer.valueOf(mem.get(2)); Integer allMemory = Integer.valueOf(mem.get(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 = logAuto.execCom(shell); // 打印shell命令執行后的結果 for (int i = 0; i < listResult.size(); i++) { System.out.println(listResult.get(i)); } // 提取CPU數據(第一行) List<String> mem = ZgxStringUtil.splitString(listResult.get(0), " "); mem.remove(0); Long allTime1 = 0L; for (int i = 0; i < mem.size(); i++) { allTime1 += Long.valueOf(mem.get(i)); } System.out.println(String.format("CPU使用總時間=%s;idle=%s", allTime1, mem.get(3))); return Pair.of(allTime1, mem.get(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.valueOf(cpuData2.getLeft().toString()) - Long.valueOf(cpuData1.getLeft().toString()); // step2 計算兩次的cpu剩余時間 Long idle = Long.valueOf(cpuData2.getRight().toString()) - Long.valueOf(cpuData1.getRight().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 = {ZgxDateUtil.getNowDate("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(); } } } }