Java 實現 ssh命令 登錄主機執行shell命令
1、SSH命令
SSH 為 Secure Shell 的縮寫,由 IETF 的網絡小組(Network Working Group)所制定;SSH 為建立在應用層基礎上的安全協議。SSH 是較可靠,專為遠程登錄會話和其他網絡服務提供安全性的協議。利用 SSH 協議可以有效防止遠程管理過程中的信息泄露問題。SSH最初是UNIX系統上的一個程序,后來又迅速擴展到其他操作平台。SSH在正確使用時可彌補網絡中的漏洞。SSH客戶端適用於多種平台。幾乎所有UNIX平台—包括HP-UX、Linux、AIX、Solaris、Digital UNIX、Irix,以及其他平台,都可運行SSH。
實際工作中,我們經常使用客戶端工具(比如:Secure CRT,Xshell,MobaXterm等)SSH到主機上,執行一些操作命令。
如何使用Java語言實現SSH 連接主機,並執行Shell命令呢?
2、Java 實現 SSH命令
1)代碼實現如下:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Calendar; import org.apache.commons.lang3.StringUtils; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; public class SshUtil { private static String DEFAULT_CHAR_SET = "UTF-8"; private static String tipStr = "=======================%s======================="; private static String splitStr = "====================================================="; /** * 登錄主機 * @return * 登錄成功返回true,否則返回false */ public static Connection login(String ip, String userName, String password){ boolean isAuthenticated = false; Connection conn = null; long startTime = Calendar.getInstance().getTimeInMillis(); try { conn = new Connection(ip); conn.connect(); // 連接主機 isAuthenticated = conn.authenticateWithPassword(userName, password); // 認證 if(isAuthenticated){ System.out.println(String.format(tipStr, "認證成功")); } else { System.out.println(String.format(tipStr, "認證失敗")); } } catch (IOException e) { System.err.println(String.format(tipStr, "登錄失敗")); e.printStackTrace(); } long endTime = Calendar.getInstance().getTimeInMillis(); System.out.println("登錄用時: " + (endTime - startTime)/1000.0 + "s\n" + splitStr); return conn; } /** * 遠程執行shell腳本或者命令 * @param cmd * 即將執行的命令 * @return * 命令執行完后返回的結果值 */ public static String execute(Connection conn, String cmd){ String result = ""; Session session = null; try { if(conn != null){ session = conn.openSession(); // 打開一個會話 session.execCommand(cmd); // 執行命令 result = processStdout(session.getStdout(), DEFAULT_CHAR_SET); //如果為得到標准輸出為空,說明腳本執行出錯了 if(StringUtils.isBlank(result)){ System.err.println("【得到標准輸出為空】\n執行的命令如下:\n" + cmd); result = processStdout(session.getStderr(), DEFAULT_CHAR_SET); }else{ System.out.println("【執行命令成功】\n執行的命令如下:\n" + cmd); } } } catch (IOException e) { System.err.println("【執行命令失敗】\n執行的命令如下:\n" + cmd + "\n" + e.getMessage()); e.printStackTrace(); } finally { if (conn != null) { conn.close(); } if (session != null) { session.close(); } } return result; } /** * 解析腳本執行返回的結果集 * @param in 輸入流對象 * @param charset 編碼 * @return * 以純文本的格式返回 */ private static String processStdout(InputStream in, String charset){ InputStream stdout = new StreamGobbler(in); StringBuffer buffer = new StringBuffer(); try { BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset)); String line = null; while((line = br.readLine()) != null){ buffer.append(line + "\n"); } } catch (UnsupportedEncodingException e) { System.err.println("解析腳本出錯:" + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("解析腳本出錯:" + e.getMessage()); e.printStackTrace(); } return buffer.toString(); } public static void main(String[] args){ String ip = "192.168.123.234"; // 此處根據實際情況,換成自己需要訪問的主機IP String userName = "root"; String password = "password"; Connection conn = SshUtil.login(ip, userName, password); String cmd = "cd /home/miracle&&pwd&&ls&&cat luna.txt"; String result = SshUtil.execute(conn, cmd); System.out.println(splitStr + "\n執行的結果如下: \n" + result + splitStr); } }
2)運行結果如下:
=======================認證成功======================= 登錄用時: 0.859s ===================================================== 【執行命令成功】 執行的命令如下: cd /home/miracle&&pwd&&ls&&cat luna.txt ===================================================== 執行的結果如下: /home/miracle luna.txt Hello, I'm SshUtil. Nice to meet you.^_^ =====================================================
3)pom.xml 引用添加如下:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> <!-- ssh --> <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency>
PS:
關於Maven依賴的 jar包 下載問題,請參考如下博文:
https://www.cnblogs.com/miracle-luna/p/11863679.html
Java 實現 bash命令
https://www.cnblogs.com/miracle-luna/p/12050728.html
Java 實現 ssh命令 登錄主機執行shell命令
https://www.cnblogs.com/miracle-luna/p/12050367.html
Java 實現 telnet命令 驗證主機端口的連通性
https://www.cnblogs.com/miracle-luna/p/12049658.html
Java 檢查IPv6地址的合法性
https://www.cnblogs.com/miracle-luna/p/12041780.html
Java 實現判斷 主機是否能 ping 通
https://www.cnblogs.com/miracle-luna/p/12026797.html