Java

Java에서 Shell호출 방법

gregorio 2018. 7. 5. 09:59

Java에서 Shell 호출 시 apache commons-exec를 사용하면 쉽게 shell을 호출하고 shell에 파라미터 전달도 가능하다.


■ 소스

import java.io.ByteArrayOutputStream;

import java.util.HashMap;

import java.util.Map;


import org.apache.commons.exec.CommandLine;

import org.apache.commons.exec.DefaultExecuteResultHandler;

import org.apache.commons.exec.DefaultExecutor;

import org.apache.commons.exec.ExecuteStreamHandler;

import org.apache.commons.exec.ExecuteWatchdog;

import org.apache.commons.exec.PumpStreamHandler;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.servlet.ModelAndView;


import ncd.spring.common.util.PropertyUtil;


@Controller

public class DeployController {


private static final Logger LOGGER = LoggerFactory.getLogger(DeployController.class);

@RequestMapping(value = "/admin/deploy.do")

public ModelAndView sourceDeploy(@RequestParam("type") String type) throws Exception {

LOGGER.info("Start Source Deploy....");

final Map<String, Object> resultMap = new HashMap<String, Object>();


String scriptFile  = PropertyUtil.getString("deploy.script.file");

String confFile = null;

if ("oz".equals(type)) {

confFile = PropertyUtil.getString("oz.deploy.config.file");

}

else {

confFile = PropertyUtil.getString("was.deploy.config.file");

}

if (scriptFile == null || confFile == null) {

resultMap.put("error", "script file or config file is null");

return new ModelAndView("ajaxMultiDataView", resultMap);

}

LOGGER.info("{},{}", scriptFile, confFile);

/** Initiate Executor **/

DefaultExecutor executor = new DefaultExecutor();

ExecuteWatchdog watchDog = new ExecuteWatchdog(60*1000);

executor.setWatchdog(watchDog);

DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ExecuteStreamHandler stream = new PumpStreamHandler(bos, bos, null);

executor.setStreamHandler(stream);

/** Initiate Command Line **/

CommandLine cmdLine = new CommandLine(PropertyUtil.getString("deploy.script.command"));

/** Set parameter to command line **/

cmdLine.addArgument(scriptFile);

cmdLine.addArgument(confFile);

cmdLine.addArgument(type);

LOGGER.info("Execute Command :: ", cmdLine.toString());

/** Execute shell **/

try {

executor.execute(cmdLine, resultHandler);

resultHandler.waitFor();

int exitCode = resultHandler.getExitValue();

String result = bos.toString();

LOGGER.info("Result :: ", result);

resultMap.put("result", result);

resultMap.put("exitCode", exitCode);

}

catch(Exception ex) {

LOGGER.error(ex.getMessage());

}

finally {

bos.close();

}

ModelAndView mav = new ModelAndView("ajaxMultiDataView", resultMap);

return mav;

}



Shell의 수행결과를 받기 위해서는 PumpStreamHandeler를 생성하고, executer에 StreamHanlder에 Set한다.