执行shell工具类
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ShellUtils {
private static final Logger logger = LoggerFactory.getLogger(ShellUtils.class);
public void executeCommand(final String command) throws IOException {
final File root = new File(".");
final Process p = Runtime.getRuntime().exec(command, null, root);
//管道sh -c ps -ef | grep -v grep
//new ProcessBuilder("sh", "-c", "ps -ef | grep -v grep");
// ProcessBuilder bulider = new ProcessBuilder(command);
// Process p = bulider.start();
Reader input = new InputStreamReader(p.getInputStream());
Reader errors = new InputStreamReader(p.getErrorStream());
for (String line : IOUtils.readLines(input)) {
if (line.startsWith("[ERROR]")) {
logger.error(line);
} else if (line.startsWith("[WARNING]")) {
logger.warn(line);
} else {
logger.info(line);
}
}
for (String line : IOUtils.readLines(errors)) {
if (line.startsWith("[ERROR]")) {
logger.error(line);
} else if (line.startsWith("[WARNING]")) {
logger.warn(line);
} else {
logger.info(line);
}
}
p.getOutputStream().close();
try {
if (p.waitFor() != 0) {
logger.warn("The command '" + command + "' did not complete successfully");
}
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
}
}