码迷,mamicode.com
首页 > 编程语言 > 详细

编写java 程序与Linux进行远程连接并运行linux下的脚本

时间:2019-05-09 00:37:42      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:inf   trace   term   exec   line   main   inux   centos   catch   

我这里是通过连接到centos6.5的大数据集群的主节点,并通过运行hadoop的启动脚本来启动hadoop

本人采用的是SSH的方式连接

通过创建maven项目来编写代码,在编写代码之前需要先导入架包

在pom.xml文件里添加以下语句

 <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>

 

 

技术图片

 

 编写连接代码:

package Studytest.com.jsion;

import java.io.IOException;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/*
  @author: Liu Yuanyuan
  purpose: test connecting remote computer and execute linux command
*/

public class TestRemoteConnect {

    public static void main(String[] args) {

        String hostname = "192.168.114.11";
        String username = "hadoop";
        String password = "666666";
        //指明连接主机的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();

                ssh.execCommand("sh /opt/modules/hadoop-2.6.0/sbin/start-all.sh");
                //ssh.execCommand("perl /root/hello.pl");
                //只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,
                //多次使用则会出现异常
                //使用多个命令用分号隔开
                //ssh.execCommand("cd /root; sh hello.sh");

                //将Terminal屏幕上的文字全部打印出来
                InputStream is = new StreamGobbler(ssh.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is));
                while (true)
                {
                    String line = brs.readLine();
                    if (line == null)
                    {
                        break;
                    }
                    System.out.println(line);
                }
            }

        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            //连接的Session和Connection对象都需要关闭
            ssh.close();
            conn.close();
        }

    }

}

 

 

运行一下代码

技术图片

 

检测集群的启动进程:

 技术图片

 

 可以看到运行成功!!!

 

编写java 程序与Linux进行远程连接并运行linux下的脚本

标签:inf   trace   term   exec   line   main   inux   centos   catch   

原文地址:https://www.cnblogs.com/braveym/p/10836055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!