后台执行linux命令
/**
*
* 方法说明:移植执行linux命令
*
* @param cmdStr 需要执行的linux命令
* @return 执行命令后的输出(如果是启动一个进程,则可能一直无法返回)
* @throws IOException
* @作者及日期:liuhengheng 2014-4-8
* @修改人及日期:zht 2017-12-7
* @修改描述:
* @其他:
*/
public static String doLinuxCmd(String cmdStr) throws IOException {
Process exec = doLinuxCmdNoOut(cmdStr);
InputStream inputStream = (InputStream) exec .getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder builder = new StringBuilder();
try {
String temp;
while ((temp = bufferedReader.readLine()) != null) {//控制台输出
builder.append(temp);
}
} catch (Exception e) {
InterfaceLogger.error("移植执行linux命令 error",e);
} finally {
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
}
log.info("linux返回值: " + builder.toString());
return builder.toString();
}
/**
*
* 方法说明:移植执行linux命令
*
* @param cmdStr
* @return
* @throws IOException
* @作者及日期:liuhengheng 2015-1-2
* @修改人及日期:zht 2017-12-7
* @修改描述:
* @其他:
*/
public static Process doLinuxCmdNoOut(String cmdStr) throws IOException {
ArrayList<String> cmds = new ArrayList<String>();
cmds.add("bash");
cmds.add("-c");
cmds.add(cmdStr);
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.redirectErrorStream(true);
Process exec = pb.start();
return exec;
}