java實現鏈接遠程服務器並執行命令的基本原理html
須要藉助Ganymed SSH的jar包: ganymed-ssh2-build210.jar java
下載地址: http://www.ganymed.ethz.ch/ssh2/ linux
API詳情: http://www.ganymed.ethz.ch/ssh2/javadoc/ch/ethz/ssh2/package-summary.htmlshell
Ganymed SSH-2 java在整個訪問過程當中擔當SSH的客戶端,因爲Linux系統自帶SSH服務,因此能夠直接訪問Linux系統並執行相關命令,而 Windows系統則須要首先安裝SSH服務。windows
當遠程服務器爲Windows系統時, 須要在遠程服務器中安裝Windows版的SSH服務,好比:freesshd。服務器
freesshd下載地址: http://www.freesshd.com/?ctt=downloadssh
freesshd安裝與配置:(能夠參考:http://www.cnblogs.com/xred/archive/2012/04/21/2461627.html)測試
1.安裝完freesshd後,首選在[Users]下添加用來遠程鏈接的win系統用戶,此處採用密碼認證的方式,容許使用shell:ui
2.而後再在【Authentication】下設置容許密碼認證方式:this
3.到[Server status]下查看SSH服務器狀態,確保啓動便可。最後點擊【肯定】便可。
4、java代碼實現遠程鏈接服務器並執行命令
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package test; import java.io.IOException; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; /* @author: Liu Yuanyuan purpose: test connecting remote computer and execute linux command */ public class TestRemoteConnect { public static void main(String[] args) { String hostname = "192.168.100.50"; int port = 22;//22 usually the default port String username = "root"; String password = "highgo"; //指明鏈接主機的IP地址 Connection conn = new Connection(hostname,port); Session ssh = null; try { //鏈接到主機 conn.connect(); //使用用戶名和密碼校驗 boolean isconn = conn.authenticateWithPassword(username, password); if (!isconn) { System.out.println("用戶名稱或者是密碼不正確"); } else { System.out.println("已經鏈接OK"); //如下是linux的示例 //將本地conf/server_start.sh傳輸到遠程主機的/opt/pg944/目錄下 SCPClient clt = conn.createSCPClient(); clt.put("conf/server_start.sh", "/opt/pg944/"); //執行命令 ssh = conn.openSession(); ssh.execCommand("sh /root/hello.sh"); //ssh.execCommand("perl /root/hello.pl"); //只容許使用一行命令,即ssh對象只能使用一次execCommand這個方法,屢次使用則會出現異常. //使用多個命令用分號隔開 //ssh.execCommand("cd /root; sh hello.sh"); /* 執行windows系統命令的示例 Session sess = conn.openSession(); sess.execCommand("ipconfig"); */ //將Terminal屏幕上的文字所有打印出來 InputStream is = new StreamGobbler(ssh.getStdout()); BufferedReader brs = new BufferedReader(new InputStreamReader(is)); while (true) { String line = brs.readLine(); if (line == null) { break; } System.out.println(line); } } } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { //鏈接的Session和Connection對象都須要關閉 if(ssh!=null) { ssh.close(); } if(conn!=null) { conn.close(); } } } }
jar包下載:http://www.jcraft.com/jsch/
實現參考:http://blog.csdn.net/allen_zhao_2012/article/details/7941631