JAvaはcentosサーバに接続し、コマンドを実行します


JAva接続にはganymed-ssh 2が必要です.
ganymed-ssh 2-build 210.jarをプロジェクトのlibに追加
package com.jms;

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 Test {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("      ");
		Connection conn = new Connection("localhost", 22);
		conn.connect();
		boolean isdenglu = conn
				.authenticateWithPassword("root", "123456");

		if (isdenglu) {
			System.out.println("ssh2    ");
		} else {
			System.out.println("    ");
		}
		
		System.out.println("    :");
		
		Session ses = conn.openSession();
		ses.execCommand("pwd");
		InputStream stdout = new StreamGobbler(ses.getStdout());

		BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true)      
        {      
            String line = br.readLine();      
            if (line == null)      
                break;      
            System.out.println(line);      
        }   

		System.out.println("    :"+ses.getExitStatus());
		ses.close();
		conn.close();
	}

}

      
ssh2      
    :
/root
    :0