熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

java應用程序遠程登錄linux並執行其命令

2013-11-23 19:29:22  來源: Java核心技術 

  在這個網址下載一個調用ssh和scp命令的jar包

  然後就可以寫程序了將上面的jar包導入MyEclipse下面是一個類的實例代碼

  package hh;

  import javaioBufferedReader; import javaioIOException; import javaioInputStream; import javaioInputStreamReader;

  import chethzsshConnection; import chethzsshSession; import chethzsshStreamGobbler;

  public class Basic

  {

  public static void main(String[] args)

  {

  String hostname = ;

  String username = boss;

  String password = qwer@;

  try

  {

  /* Create a connection instance */

  Connection conn = new Connection(hostname);

  /* Now connect */

  nnect();

  /* Authenticate */

  boolean isAuthenticated = connauthenticateWithPassword(username password);

  if (isAuthenticated == false)

  throw new IOException(Authentication failed);

  /* Create a session */

  Session sess = connopenSession();

  //sessexecCommand(uname a && date && uptime && who);

  sessexecCommand(ps aux );

  Systemoutprintln(Here is some information about the remote host:);

  InputStream stdout = new StreamGobbler(sessgetStdout());

  BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

  while (true)

  {

  String line = brreadLine();

  if (line == null)

  break;

  Systemoutprintln(line);

  }

  /* Show exit status if available (otherwise null) */

  Systemoutprintln(ExitCode: + sessgetExitStatus());

  /* Close this session */

  sessclose();

  /* Close the connection */

  connclose();

  }

  catch (IOException e)

  {

  eprintStackTrace(Systemerr); Systemexit();

  }

  }

  }

  在控制台我們將看到輸出結果

  很簡單不過理解其中的原理要費一番的周折了以後再給大家講一些原理方面的東西


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26951.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.