idea+maven+ ganymed-ssh2远程调用hadoop程序

                                                        这篇博客是采用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环境的访问路径的配置








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值