Java进行shell操作

public class ShellUtil {
    private static final Logger logger = LoggerFactory.getLogger(ShellUtil.class);
    
    /**
     * 执行指定命令
     * @param command
     * @return
     */
    public static ShellResult execute(String command) {
        List<String> cmdComponents = Lists.newArrayList();
        cmdComponents.add("sh");
        cmdComponents.add("-c");
        cmdComponents.add(command);

        /**进程句柄*/
        ProcessBuilder processBuilder = new ProcessBuilder(cmdComponents);
        Process process;
        try {
            process = processBuilder.start();
            process.waitFor();
        } catch (IOException ex) {
            String cmdStartExceptionMsg = String.format("启动命令失败, command:%s, 原因:%s", command, ex.toString());
            logger.error(cmdStartExceptionMsg, ex);

            return ShellResult.buildFailResult(cmdStartExceptionMsg);
        } catch (InterruptedException ex) {
            String cmdIntExceptionMsg = String.format("命令执行被中断, command:%s, 原因:%s", command, ex.toString());
            logger.error(cmdIntExceptionMsg, ex);

            return ShellResult.buildFailResult(cmdIntExceptionMsg);
        }

        ShellResult runResult = readResult(process);
        if (!runResult.isSuccess()) {
            String resultReadError = String.format("命令执行结果读取失败, command:%s, 原因:%s",
                                                        command, runResult.getResultMessage());
            logger.error(resultReadError);
        }

        return runResult;
    }

    private static ShellResult readResult(Process process) {

        // 取得命令输出
        List<String> outStrList = readFromStream(process.getInputStream());
        if (outStrList == null) {
            return ShellResult.buildFailResult("读取命令标准输出发生异常");
        }

        // 取得命令错误
        List<String> errStrList = readFromStream(process.getErrorStream());
        if (errStrList == null) {
            return ShellResult.buildFailResult("读取命令标准错误发生异常");
        }

        return ShellResult.buildSuccessResult(process.exitValue(), outStrList, errStrList);
    }

    private static List<String> readFromStream(InputStream ins) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
        List<String> strList = Lists.newArrayList();
        try {
            String line = reader.readLine();
            while (line != null) {
                strList.add(line);
                line = reader.readLine();
            }
        } catch (IOException ex) {
            String readError = "读取命令执行结果时出现读取IO异常";
            logger.error(readError, ex);
            strList = null;
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                String closeError = "读取命令执行结果时出现关闭IO异常";
                logger.error(closeError, ex);
                strList = null;
            }
        }
        return strList;
    }
}

 

@Data
public class ShellResult {
    private boolean success;
    private String resultMessage;
    private int exitValue;
    private List<String> stdOut;
    private List<String> stdErr;

    public static ShellResult buildSuccessResult(int exitValue,
                                                 List<String> stdOut,
                                                 List<String> stdErr) {
        ShellResult shellResult = new ShellResult();
        shellResult.setSuccess(true);
        shellResult.setResultMessage("");
        shellResult.setExitValue(exitValue);
        shellResult.setStdOut(stdOut);
        shellResult.setStdErr(stdErr);

        return shellResult;
    }

    public static ShellResult buildFailResult(String resultMessage) {
        ShellResult shellResult = new ShellResult();
        shellResult.setSuccess(false);
        shellResult.setResultMessage(resultMessage);

        return shellResult;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值