You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

72 lines
2.1 KiB

package com.insigma.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* CommandImpUtil
*
* @author admin
*/
@Slf4j
@SuppressWarnings("DuplicatedCode")
public class LinuxCommandUtil implements Runnable {
private String command;
public LinuxCommandUtil(String command) {
this.command = command;
}
@Override
public void run() {
Process process;
int exitVal = 0;
try {
log.debug("准备执行命令:{}",command);
process = Runtime.getRuntime().exec(command);
// Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。
//针对这种情况,我们只需要将子进程的stream重定向出来即可。
new RunCmdStreamThread(process.getInputStream(), "INFO").start();
new RunCmdStreamThread(process.getErrorStream(), "ERR").start();
exitVal = process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
if (exitVal != 0) {
log.error("执行命令发生异常:{}", exitVal);
throw new RuntimeException("shell任务执行失败");
}
}
static class RunCmdStreamThread extends Thread {
InputStream is;
String printType;
RunCmdStreamThread(InputStream is, String printType) {
this.is = is;
this.printType = printType;
}
@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
log.debug("输出:{}>{}", printType, line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}