1.pom.xml引入
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
2.java程式碼
package com.ruoyi.project.system.learn.controller; import ch.ethz.ssh2.ChannelCondition; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class SSHClient { private String ip; private String username; private String password; private String charset = Charset.defaultCharset().toString(); private static final int TIME_OUT = 1000 * 5 * 60; private Connection conn; public SSHClient(String ip, String username, String password) { this.ip = ip; this.username = username; this.password = password; } /** * 登入指遠端伺服器 * @return * @throws IOException */ private boolean login() throws IOException { conn = new Connection(ip); conn.connect(); return conn.authenticateWithPassword(username, password); } public int exec(String shell) { int ret = -1; try { if (login()) { Session session = conn.openSession(); session.execCommand(shell); session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); ret = session.getExitStatus(); // 獲得標準輸出流 InputStream is = new StreamGobbler(session.getStdout()); BufferedReader brs = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> result = new ArrayList<>(); for (String line = brs.readLine(); line != null; line = brs.readLine()) { System.out.println(line); } } else { throw new Exception("登入遠端機器失敗" + ip); // 自定義異常類 實現略 } }catch(Exception e){ e.printStackTrace(); } finally { if (conn != null) { conn.close(); } } return ret; } public static void main(String[] args){ try { SSHClient sshClient = new SSHClient("IP地址", "使用者名稱", "密碼"); sshClient.exec("/root/free.sh"); //指令碼檔案 } catch (Exception e) { e.printStackTrace(); } } }
3.指令碼檔案free.sh,賦予許可權:chmod +x free.sh
# FNR = 行, print = 列 #記憶體 MEM_USED=$(free | awk 'FNR == 2 {print $3}') MEM_TOTAL=$(free | awk 'FNR == 2 {print $2}') echo $MEM_TOTAL $MEM_USED #磁碟使用率 DISK_USAGE=$(df -h | awk 'FNR == 6 {sub(/%/, ""); print $5}') echo $DISK_USAGE #檢視java程序cpu使用率 echo $(top -bn 1 | grep "java" | awk '{print $9}') #IO iowait=`vmstat |awk '{if(NR==3) print $16}'` echo ${iowait} #檢視RuoYi.jar程序ID id=`ps -ef | grep RuoYi.jar | grep -v grep | awk '{print $2}'` echo $id