1.maven的POM.xml需要配置包
<dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency>
2.直接上代码
package maven;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class RemoteShellTool {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
List<String> result=new ArrayList<String>();
Connection connection = new Connection("IP");
connection.connect();//连接
connection.authenticateWithPassword("username","password");//认证
Session session=connection.openSession();
session.execCommand("/opt/cloudera/parcels/CDH/bin/hdfs dfs -ls /");
InputStream is = new StreamGobbler(session.getStdout());//获得标准输出流
BufferedReader brs = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String temp = "";
while ((temp=brs.readLine()) != null) {
String[] a = temp.split("\\s+");
if(a.length > 7 ){
result.add(a[a.length-1]);
}
}
System.out.println(result);
if (session != null) {
session.close();
}
session.close();
brs.close();
}
}
将IP换成自己的IP地址,用户名密码修改为自己的。
3.当我们执行多个脚本的时候,会出现有一个脚本正在执行的错误,这时候我们需要执行多个Session session=connection.openSession();