私はこの種のJavaアプリケーションに不慣れで、SSHを使用してリモートサーバーに接続し、コマンドを実行し、プログラミング言語としてJavaを使用して出力を取得する方法に関するサンプルコードを探しています。
6 に答える
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();
以下は、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);
}
}
このJavaベースのリモートコマンド実行用フレームワークをご覧ください。SSH 経由: https://github.com/jkovacic/remote-exec JSch (この実装では ECDSA 認証もサポートされています) または Ganymed (これら 2 つのライブラリのいずれかで十分です) の 2 つのオープンソース SSH ライブラリに依存しています。一見すると少し複雑に見えるかもしれませんが、SSH 関連のクラス (サーバーとユーザーの詳細を提供する、暗号化の詳細を指定する、OpenSSH 互換の秘密鍵を提供するなど) をたくさん準備する必要がありますが、SSH 自体は非常に複雑です。それも)。一方、モジュラー設計により、より多くの SSH ライブラリを簡単に含めることができ、他のコマンドの出力処理やインタラクティブなクラスなどを簡単に実装できます。
私は数年前にこれにganymedeを使用しました... http://www.cleondris.ch/opensource/ssh2/