需要下载ganymed-ssh2-262.jar
package ganymed; 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 SShUtil {
public static String execShellScript(String host, String username,
String password, String cmd, int port) throws IOException { System.out.println(("running SSH cmd [" + cmd + "]"));
Connection connection = null; Session sess = null; InputStream stdout = null; BufferedReader br = null; StringBuffer buffer = new StringBuffer("exec result:");
buffer.append(System.getProperty("line.separator"));// 换行
try { connection = new Connection(host, port);
connection.connect(); if (!connection.authenticateWithPassword(username, password)) {
throw new RuntimeException("authenticateWithPassword failed");
} sess = connection.openSession(); sess.execCommand(cmd); stdout = new StreamGobbler(sess.getStdout()); br = new BufferedReader(new InputStreamReader(stdout)); while (true) {
String line = br.readLine();
if (line == null) {
break;
}
buffer.append(line);
buffer.append(System.getProperty("line.separator"));// 换行
System.out.println(line);
} } finally {
if(br != null){
br.close();
}
if(sess != null){
sess.close();
}
if(connection != null){
connection.close();
}
} return buffer.toString(); } public static void main(String[] args) {
String cmd = "cd /usr/local/mysql/bin&&./ndb_mgm -e show";
try {
String info = execShellScript("192.168.1.240", "root", "test",cmd,22);
} catch (IOException e) {
e.printStackTrace();
} } }