ch.ethz.ssh2.Connection在Java中的使用

首先需要先建立一個Connection對象,構造函數有如下兩種情況:

//準備一個新Connection對象,然後可以使用該對象建立與指定SSH-2服務器的連接。

Connection(java.lang.String hostname)

//準備一個新Connection對象,然後可以使用該對象建立與指定SSH-2服務器的連接

Connection(java.lang.String hostname, int port)

然後通過調用Connection對象的connect()方法進行連接,接著需要通過authenticateWithPassword()方法進行用戶名和密碼驗證,這樣基本完成與服務器的連接。執行具體的命令時通過開啟Session來實現的,通過調用Connection對象的openSession()方法來獲取一個Session對象,通過調用Session對象的execCommand()方法執行具體的命令,需要注意的是一個Session對象只能遠程執行一條語句,所以如果讀者要執行多條命令,有兩種選擇,一種是將命令組合成一條命令,執行一次,另一種方法是執行一條命令後就關閉Session對象,但是不要關閉Connection對象,繼續開啟一個新的Session對象來執行下一條命令,依次類推,執行完所有的命令,使用後記得關閉Connection對象。由於上面附有有文檔的接口,所以只是闡述的調用的方法,沒有說明每個方法所需要的參數,讀者可根據下面的代碼案例進行理解,在使用時還是建議根據文檔接口選擇適合自己的方法:

  • import java.io.BufferedReader;

  • import java.io.IOException;

  • import java.io.InputStream;

  • import java.io.InputStreamReader;

  • import ch.ethz.ssh2.Connection;

  • import ch.ethz.ssh2.Session;

  • import ch.ethz.ssh2.StreamGobbler;

  • public class SSHTest{

  • public static void main(String[] args) {

  • String hostname = "192.168.192.128";

  • String username = "root";

  • String password = "root";

  • try {

  • Connection conn = new Connection(hostname);

  • conn.connect();

  • //進行身份認證

  • boolean isAuthenticated = conn.authenticateWithPassword(

  • username,password);

  • if (isAuthenticated == false)

  • throw new IOException("Authentication failed.");

  • //開啟一個Session

  • Session sess = conn.openSession();

  • sess.execCommand("cat haha.txt");

  • //獲取返回輸出

  • InputStream stdout = new StreamGobbler(sess.getStdout());

  • //返回錯誤輸出

  • InputStream stderr = new StreamGobbler(sess.getStderr());

  • BufferedReader stdoutReader = new BufferedReader(

  • new InputStreamReader(stdout));

  • BufferedReader stderrReader = new BufferedReader(

  • new InputStreamReader(stderr));

  • System.out.println("Here is the output from stdout:");

  • while (true) {

  • String line = stdoutReader.readLine();

  • if (line == null)

  • break;

  • System.out.println(line);

  • }

  • System.out.println("Here is the output from stderr:");

  • while (true) {

  • String line = stderrReader.readLine();

  • if (line == null)

  • break;

  • System.out.println(line);

  • }

  • //關閉Session

  • sess.close();

  • //關閉Connection

  • conn.close();

  • } catch (IOException e) {

  • e.printStackTrace(System.err);

  • System.exit(2);

  • }

  • }

    }


分享到:


相關文章: