Skip to content

Instantly share code, notes, and snippets.

@shalk
Created January 9, 2018 08:28
Show Gist options
  • Select an option

  • Save shalk/c1feb37d475740e2876dc34a7f21b506 to your computer and use it in GitHub Desktop.

Select an option

Save shalk/c1feb37d475740e2876dc34a7f21b506 to your computer and use it in GitHub Desktop.
java 执行命令
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.LogOutputStream;
import org.apache.commons.exec.PumpStreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 执行vic命令行 进行日志,异常,返回值等的控制
* @author shalk
*
*/
public class CommandRunner {
private final static Logger logger = LoggerFactory.getLogger(CommandRunner.class);
// 创建VCH 默认超时2分钟
private static final int timeout = 2;
/**
* 解析参数 不处理引号
* @param prog
* @param cmds
* @return
* @throws Exception
*/
public static CMDResult runCmd(String prog, String[] cmds, CMDResult result) throws Exception {
return runCmd(prog, cmds, false, result);
}
public static CMDResult runCmd(String prog, String[] cmds, boolean handleQuota, CMDResult result) throws Exception {
CommandLine cmdline = new CommandLine(prog);
cmdline.addArguments(cmds, handleQuota);
return runCmd(cmdline, result);
}
public static CMDResult runCmd(String cmd, CMDResult result) throws Exception {
CommandLine cmdline = CommandLine.parse(cmd);
return runCmd(cmdline, result);
}
public static CMDResult runCmd(CommandLine cmdline, CMDResult result) throws Exception {
logger.info("开始执行cmd:"+ cmdline.toString());
Executor exec = new DefaultExecutor();
CMDResult ret = result;
StringBuffer stdout = ret.getStdout();
StringBuffer stderr = ret.getStderr();
// 超时
ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout * 60 * 1000);
exec.setWatchdog(watchdog);
// output,err 重定向到日志
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(new LogOutputStream() {
@Override
protected void processLine(String line, int logLevel) {
logger.info(line);
stdout.append(line).append("\n");
}
}, new LogOutputStream() {
@Override
protected void processLine(String line, int logLevel) {
logger.error(line);
stderr.append(line).append("\n");
}
});
exec.setStreamHandler(pumpStreamHandler);
// 非阻塞
// ExecuteResultHandler handle1 = new DefaultExecuteResultHandler();
try {
int exitValue = exec.execute(cmdline);
ret.setExitValue(exitValue);
if (exitValue != 0) {
System.out.println("执行出错");
logger.error("执行失败: eixtValue = " + exitValue);
} else {
System.out.println("执行成功");
logger.info("执行成功: exitValue = " + exitValue);
}
} catch (ExecuteException e) {
logger.error("err", e);
logger.error("cmd:" + cmdline.toString());
logger.error("执行命令异常出错");
ret.setExitValue(e.getExitValue());
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment