33

私はこの種のJavaアプリケーションに不慣れで、SSHを使用してリモートサーバーに接続し、コマンドを実行し、プログラミング言語としてJavaを使用して出力を取得する方法に関するサンプルコードを探しています。

4

6 に答える 6

23

Runtime.exec() Javadoc をご覧ください

Process p = Runtime.getRuntime().exec("ssh myhost");
PrintStream out = new PrintStream(p.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

out.println("ls -l /home/me");
while (in.ready()) {
  String s = in.readLine();
  System.out.println(s);
}
out.println("exit");

p.waitFor();
于 2010-03-25T09:53:48.620 に答える
12

JSch は、リモート マシンでコマンドを実行するのに役立つ SSH2 の純粋な Java 実装です。ここで見つけることができ、ここにいくつかの例があります

使用できますexec.java

于 2011-09-22T07:21:17.673 に答える
7

以下は、Java で SSH を行う最も簡単な方法です。以下のリンクから任意のファイルをダウンロードして解凍し、解凍したファイルから jar ファイルを追加して、プロジェクト http://www.ganymed.ethz.ch/ssh2/のビルド パスに追加し 、以下の方法を使用します。

public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{
        System.out.println("inside the ssh function");
        try
        {
            Connection conn = new Connection(serverIp);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");        
            ch.ethz.ssh2.Session sess = conn.openSession();
            sess.execCommand(command);  
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            System.out.println("the output of the command is");
            while (true)
            {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            System.out.println("ExitCode: " + sess.getExitStatus());
            sess.close();
            conn.close();
        }
        catch (IOException e)
        {
            e.printStackTrace(System.err);

        }
    }
于 2016-05-24T04:27:54.463 に答える
3

このJavaベースのリモートコマンド実行用フレームワークをご覧ください。SSH 経由: https://github.com/jkovacic/remote-exec JSch (この実装では ECDSA 認証もサポートされています) または Ganymed (これら 2 つのライブラリのいずれかで十分です) の 2 つのオープンソース SSH ライブラリに依存しています。一見すると少し複雑に見えるかもしれませんが、SSH 関連のクラス (サーバーとユーザーの詳細を提供する、暗号化の詳細を指定する、OpenSSH 互換の秘密鍵を提供するなど) をたくさん準備する必要がありますが、SSH 自体は非常に複雑です。それも)。一方、モジュラー設計により、より多くの SSH ライブラリを簡単に含めることができ、他のコマンドの出力処理やインタラクティブなクラスなどを簡単に実装できます。

于 2012-05-21T20:21:53.433 に答える
1

私は数年前にこれにganymedeを使用しました... http://www.cleondris.ch/opensource/ssh2/

于 2010-03-25T11:30:51.057 に答える