使用JAVA执行shell

引入依赖1         <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>
创建Connection并连接1 Connection conn = new Connection("47.112.138.184");
2 conn.connect();
需要账号密码登录的机器,进行校验,返回布尔值1 boolean login = conn.authenticateWithPassword(ACCOUNT, PASSWORD);
打开回话,并执行shell指令1 Session session = conn.openSession();
2 session.execCommand("cd /home/scripts;ls");    //多条指令时,用英文半角顿号隔开
getStdout()方法可拿到一个输入流,即远端控制台返回的数据
1 StreamGobbler gobbler = new StreamGobbler(session.getStdout());
2 BufferedReader reader = new BufferedReader(new InputStreamReader(gobbler));

 流处理    StringBuilder result = new StringBuilder();
    while(true) {
        String readLine = reader.readLine();
        if (readLine == null) {
            reader.close();
            break;
        }
        result.append(readLine).append("\n\r");
    }
getExitStatus()可获取指令执行结果,0-成功;1-失败
1 Integer exitStatus = session.getExitStatus();

切记:关闭reader、session、conn

以下为完整可用的工具类 1      Connection conn = new Connection("IP");
        conn.connect();
        boolean login = conn.authenticateWithPassword("ACCOUNT", "PASSWORD");
        if (login) {
            Session session = conn.openSession();
            session.execCommand("cd /home/scripts;ls");
            StreamGobbler gobbler = new StreamGobbler(session.getStdout());
            BufferedReader reader = new BufferedReader(new InputStreamReader(gobbler));
            
            StringBuilder result = new StringBuilder();
            while(true) {
                String readLine = reader.readLine();
                if (readLine == null) {
                    reader.close();
                    break;
                }
                result.append(readLine).append("\n\r");
            }
            
            Integer exitStatus = session.getExitStatus();
            session.close();

            System.err.println("result:"+result);
            System.err.println("exit ? " + exitStatus);
        }
        
        if (conn != null) {
            conn.close();
        }

相关推荐