Java で ssh や scp を呼び出す(2)

今日はもう眠いので、単純に1つのコマンド実行まで。

import java.io.*;
import ch.ethz.ssh2.*;

public class SshTest {
	private static final String hostname = "ホスト名";
	private static final String userid   = "ユーザ名";
	private static final String password = "パスワード";

	private static final int BUFFER_SIZE = 4096;

	public static void main(String[] arg) {
		try {
			SshTest test = new SshTest();
			test.doProc();
		} catch (IOException ex) {ex.printStackTrace();}
	}

	public void doProc() throws IOException {
		// connect & login
		Connection conn = new Connection(hostname);
		ConnectionInfo info = conn.connect();
		boolean result = conn.authenticateWithPassword(userid, password);

		if (result) {
			// exec "ls -l"
			Session session = conn.openSession();
			session.execCommand("ls -l");
			System.out.println(streamToString(session.getStdout()));
			session.close();
		}
		conn.close();
	}

	// read InputStream and return output as String
	private String streamToString(InputStream in) throws IOException {
		byte[] buf = new byte[BUFFER_SIZE];
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int len;
		while ((len = in.read(buf, 0, BUFFER_SIZE))>0) out.write(buf, 0, len);
		return out.toString();
	}
}

認証して Connect を取得するところまでは scp と一緒。
その後、 openSession() でセッションインスタンスを取得して、execCommand() で実行したいコマンド文字列を渡せばいい。
実行結果は session.getStdout() で得られる InputStream を読み出す。


ということで、一見、1コマンドの実行もとても簡単に記述できる。
でも、接続先でのエラーの処理や、複数コマンドの実行を「賢く」やりたいなあ、と思ったらさすがにいろいろ面倒が起きてくるのだが、それはまた今度。