这篇博客是采用JAVA SSH2协议实现的,通过在本地远程去调用linux服务器,从而实现运行jar包中的hadoop程序
在pom中配置ssh2jar包
<!--ssh2架包-->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
</dependencies>
在方法里实现调用,并在cmd里写上你要执行的命令,我这里是调用hadoopjar包,并同时把执行成功之后所生成的文件放在输出目录,传入出入和输出路径等等,使用多个命令中间用分号隔开。
public class SSh2 {
private static String processStdout(InputStream in, String charset){
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
String line=null;
while((line=br.readLine()) != null){
buffer.append(line+"\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public void execmd(String inputUrl, String outputUrl, String endpoint, String starttime, String endtime)
{
String hostname = "192.168.50.228";
String username = "hduser";
String password = "1234567";
String result="";
//指明连接主机的IP地址
Connection conn = new Connection(hostname);
Session ssh = null;
try {
//连接到主机
conn.connect();
//使用用户名和密码校验
boolean isconn = conn.authenticateWithPassword(username, password);
if(!isconn){
System.out.println("用户名称或者是密码不正确");
}else{
System.out.println("已经连接OK");
ssh = conn.openSession();
String cmd="hadoop jar /usr/hadoop/hadoop-2.6.0/share/hadoop/mapreduce/threePhaseNew.jar /input/rtu_voltage0001.txt /output/VoltageBalance21 1000085,1000210,1000328 20160101 20160331;hdfs dfs -get /output/threePhaseVoltageBalance /usr/hadoop/hadoop-2.6.0/bigdata_out";
//使用多个命令用分号隔开
ssh.execCommand(cmd);
//只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常
result=processStdout(ssh.getStdout(),"utf-8");
//如果为得到标准输出为空,说明脚本执行出错了
if(StringUtils.isBlank(result)){
result=processStdout(ssh.getStderr(),"utf-8");
System.out.print(result);
}
}
//连接的Session和Connection对象都需要关闭
ssh.close();
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果出现执行成功却没有文件生成的情况,需要改一下hadoop环境的访问路径的配置