java调用shell

java调用shell

摘要

java调用shell

java调用shell

Apache Commons Exec
https://commons.apache.org/proper/commons-exec/tutorial.html

Demo
https://github.com/daodaovps/CommonsExecTest

maven

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.3</version>
</dependency>

测试01

package net.javablog;

import org.apache.commons.exec.*;


public class App {


    /**
     * 官方手册: https://commons.apache.org/proper/commons-exec/tutorial.html
     *
     * @param args
     */

    public static void main(String[] args) {

        testRuntime2();

    }


    private static void testRuntime() {


        try {
            String line = "/home/zhu/test/test.sh";
            CommandLine cmdLine = CommandLine.parse(line);
            DefaultExecutor executor = new DefaultExecutor();

            //设置预期的exitvalue  , 如果不是的话会跑出异常.  org.apache.commons.exec.ExecuteException: Process exited with an error: 0 (Exit value: 0)
            executor.setExitValue(1);

            //设置脚本执行时间,超过指定的时间会自动中断执行   org.apache.commons.exec.ExecuteException: Process exited with an error: 143 (Exit value: 143)
            ExecuteWatchdog watchdog = new ExecuteWatchdog(5000);
            executor.setWatchdog(watchdog);


            int exitValue = executor.execute(cmdLine);
            System.out.println("exitValue " + exitValue);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 不抛出异常,异常作为参数包装起来
     */
    private static void testRuntime2() {
        try {
            CommandLine cmdLine = new CommandLine("/home/zhu/test/test.sh");
            cmdLine.addArgument("1111",true);
            cmdLine.addArgument("2222",true);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(3 * 1000);
            Executor executor = new DefaultExecutor();
            executor.setExitValue(0);
            executor.setWatchdog(watchdog);
            executor.execute(cmdLine, resultHandler);

            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitValue = resultHandler.getExitValue();
            Exception e = resultHandler.getException();
            System.out.println("exitValue " + exitValue);
            System.out.println("Exception " + e.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

测试02

直接返回shell的output文本输出
如果有错,则返回空字符串,并且设置了超时为1分钟.

package com.xender.snapshow.util;

import org.apache.commons.exec.*;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * Created by zsl on 2017/7/18.
 */
public class Shell {

    private static final Logger log = LoggerFactory.getLogger(Shell.class);


    /**
     * 超时1分钟 , 停止解析.  直接返回空
     *
     * @param cmd
     * @return
     */
    public static String getCmdResult(String cmd ,List<String> params) {

        try {

            log.info("cmd  {}" ,cmd);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();

            CommandLine cmdLine = new CommandLine(cmd);
            if(!Lang.isEmpty(params))
            {
                for (int i = 0; i < params.size(); i++) {
                    cmdLine.addArgument(params.get(i), false);
                }
            }

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
            Executor executor = new DefaultExecutor();
//            executor.setWorkingDirectory(new File(System.getProperty("user.home")));
//            executor.setExitValue(0);
            executor.setWatchdog(watchdog);

            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
            executor.setStreamHandler(streamHandler);

            executor.execute(cmdLine, resultHandler);

            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitValue = resultHandler.getExitValue();
            Exception e = resultHandler.getException();

            String out = outputStream.toString("UTF8");
            String error = errorStream.toString("UTF8");
            System.out.println("out \n" + out);
            System.out.println("error \n" + error);

            System.out.println("exitValue " + exitValue);
            System.out.println("Exception " + (e == null ? "empty" : e.getMessage()));

            if (!Strings.isBlank(error) || !Lang.isEmpty(e)) {
                log.error(error);
                log.error(Lang.getStackTrace(e));
                throw  new RuntimeException(e);
            }

            return out+"\r\n" ;

        } catch (Exception e) {
            e.printStackTrace();
            log.error(Lang.getStackTrace(e));
        }

        return "";

    }
}