使用JAVA程式碼通過SSH訪問遠端windows,獲取磁碟資訊
阿新 • • 發佈:2019-02-02
package ***; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; @Service("listenSystemServiceImpl") public class ListenSystemServiceImpl{ private String HOST_NAME = "192.168.12.11"; //IP地址 private int PORT = 22; //埠號 private String LOGIN_NAME = "Administrator"; //登入賬號 private String PASS_WORD = "admin"; //登入密碼 private String CMD_WINDOWS="E:"; //windows命令 private long totalSpace = 0; private long freeSpace = 0; private long usedSpace = 0; /** * 獲取磁碟資訊 * * @return */ public Map getDiskInfo() { Map map = new HashMap(); Connection conn = new Connection(HOST_NAME, PORT); Session ssh = null; try { conn.connect(); boolean flag = conn.authenticateWithPassword(LOGIN_NAME, PASS_WORD); if (!flag) { System.out.println("使用者名稱或密碼錯誤"); } else { System.out.println("連線成功"); ssh = conn.openSession(); //windows map = this.getDiskByWindows(ssh,map); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (ssh != null) { ssh.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } return map; } /** * 用於windows * @param map * @return * @throws IOException */ public Map getDiskByWindows(Session ssh,Map map) throws IOException{ ssh.execCommand("wmic LogicalDisk where \"Caption='"+ CMD_WINDOWS+"'\" get FreeSpace,Size /value"); InputStream stdout = new StreamGobbler(ssh.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); String len = null; while((len = br.readLine()) != null){ if(len.startsWith("FreeSpace")){ String[] str = len.split("="); freeSpace = Long.parseLong(str[1])/ 1024 / 1024 / 1024; } if(len.startsWith("Size")){ String[] str = len.split("="); totalSpace = Long.parseLong(str[1])/ 1024 / 1024 / 1024; } } usedSpace = totalSpace - freeSpace; System.out.println("總空間大小 : " + totalSpace + "G"); System.out.println("剩餘空間大小 : " + freeSpace + "G"); System.out.println("已用空間大小 : " + usedSpace + "G"); map.put("total", totalSpace); map.put("free", freeSpace); map.put("used", usedSpace); return map; } }