All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.shoothzj.javatool.util.ShellUtil Maven / Gradle / Ivy

The newest version!
package com.github.shoothzj.javatool.util;

import com.github.shoothzj.javatool.module.ShellResult;
import java.io.InputStream;

public class ShellUtil {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ShellUtil.class);

    public static ShellResult executeScript(String script) {
        return ShellUtil.executeCmd("bash -x " + script);
    }

    public static ShellResult executeCmd(String[] cmd) {
        log.info("exec command array {}", String.join(";", cmd));
        String inputContent = "";
        String errorContent = "";
        int ret = -1;
        try {
            Process pid = Runtime.getRuntime().exec(cmd);
            ret = pid.waitFor();
            InputStream inputStream = pid.getInputStream();
            InputStream errorStream = pid.getErrorStream();
            inputContent = IoUtil.read2String(inputStream);
            errorContent = IoUtil.read2String(errorStream);
            log.error("command is {}, result is {}, input content is [{}], error content is [{}]", cmd, ret, inputContent, errorContent);
            return new ShellResult(ret, inputContent, errorContent);
        } catch (Exception e) {
            log.error("Execute command exception. [{}], input content is [{}], error content is [{}]", e.getMessage(), inputContent, errorContent);
            return new ShellResult(ret, inputContent, errorContent, e);
        }
    }

    public static ShellResult executeCmd(String cmd) {
        log.info("exec command {}", cmd);
        String inputContent = "";
        String errorContent = "";
        int ret = -1;
        try {
            Process pid = Runtime.getRuntime().exec(cmd);
            ret = pid.waitFor();
            InputStream inputStream = pid.getInputStream();
            InputStream errorStream = pid.getErrorStream();
            inputContent = IoUtil.read2String(inputStream);
            errorContent = IoUtil.read2String(errorStream);
            log.error("command is {}, result is {}, input content is [{}], error content is [{}]", cmd, ret, inputContent, errorContent);
            return new ShellResult(ret, inputContent, errorContent);
        } catch (Exception e) {
            log.error("Execute command exception. [{}], input content is [{}], error content is [{}]", e.getMessage(), inputContent, errorContent);
            return new ShellResult(ret, inputContent, errorContent, e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy