Java执行windows和linux命令
温馨提示:
本文最后更新于 2024年12月11日,已超过 142 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
一. windows命令
//需要导入线程池
@Resource
private ThreadPoolExecutor executor;
/**
* 在windows场景下,执行单个cmd命令
*
* @param command windows场景单行命令
* @return 执行结果文本
* @throws IOException IO异常
* @throws ExecutionException 执行异常
* @throws InterruptedException 记时异常
* @throws TimeoutException 超时异常
*/
private static List<String> executeCommand(String command, long timeoutSeconds)
throws IOException, ExecutionException,
InterruptedException, TimeoutException {
Process process = Runtime.getRuntime().exec(command);
// 命令执行错误回显流、命令执行的回显流
List<String> outInfos = getEchoInfos(process.getInputStream(), process.getErrorStream(), timeoutSeconds);
process.destroy();
return outInfos;
}
//执行多个命令
private List<String> executeCommands(List<String> commands) throws IOException, ExecutionException,
InterruptedException, TimeoutException {
Process process = Runtime.getRuntime().exec("cmd");
// 同一个会话命令持续输入流
try (OutputStream processIn = process.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(processIn);
BufferedWriter bw = new BufferedWriter(osw)) {
for (String command : commands) {
bw.write(command);
bw.newLine();
}
bw.flush();
}
// 命令执行的回显流、命令执行错误回显流
List<String> outInfos = getEchoInfos(process.getInputStream(), process.getErrorStream(), 30);
process.destroy();
return outInfos;
}
private List<String> getEchoInfos(InputStream processOut, InputStream processErr, long timeoutSeconds) throws ExecutionException,
InterruptedException, TimeoutException {
Future<List<String>> outFuture = executor.submit(() -> readEcho(processOut));
Future<List<String>> errFuture = executor.submit(() -> readEcho(processErr));
List<String> outInfos = outFuture.get(timeoutSeconds, TimeUnit.SECONDS);
List<String> errInfos = errFuture.get(timeoutSeconds, TimeUnit.SECONDS);
if (CollectionUtil.isNotEmpty(errInfos)) {
log.warn("execute commands error: {}", errInfos);
}
return outInfos;
}
private List<String> readEcho(InputStream echoStream) throws IOException {
try (InputStream is = echoStream;
InputStreamReader isr = new InputStreamReader(is, Charset.forName("GBK"));
// InputStreamReader isr = new InputStreamReader(is, ApplicationContext.isWindows() ? Charset.forName("GBK") : StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
List<String> echoInfos = new ArrayList<>();
String echoInfo;
while ((echoInfo = br.readLine()) != null) {
echoInfos.add(echoInfo);
}
return echoInfos;
}
}
二. linux命令
/**
* 直接执行(通过bash来执行命令 比如./xxxxx.sh)
*
* @param command sh文件+参数,空格分开
* @param timeoutSeconds 等待超时时间
* @return 执行结果
*/
public static List<String> executeLinuxSh(String command, long timeoutSeconds) {
log.info("the execute command is: {}", command);
if (StrUtil.isEmpty(command)) {
log.warn("the execute command is empty.");
return Collections.emptyList();
}
Process process = null;
List<String> outInfos = Collections.emptyList();
try {
process = Runtime.getRuntime().exec(command);
outInfos = getEchoInfos(process.getInputStream(), process.getErrorStream(), timeoutSeconds);
} catch (Exception e) {
log.error("System execute command failed!", e);
} finally {
if (Objects.nonNull(process)) {
process.destroy();
}
}
return outInfos;
}
/**
* linux场景执行命令(通过sh来执行 sh xxxxx.sh形式)
*
* @param command command 执行的命令
* @param timeoutSeconds 等待超时时间
* @return 执行结果
*/
public static List<String> executeLinuxCommandWaitTimeout(String command, long timeoutSeconds) {
if (StrUtil.isEmpty(command)) {
log.warn("the execute command is empty.");
return Collections.emptyList();
}
String[] cmdArr = {"/bin/sh", "-c", command};
Process process = null;
List<String> outInfos = Collections.emptyList();
try {
process = Runtime.getRuntime().exec(cmdArr);
outInfos = getEchoInfos(process.getInputStream(), process.getErrorStream(), timeoutSeconds);
} catch (Exception e) {
log.error("System execute command failed!", e);
} finally {
if (Objects.nonNull(process)) {
process.destroy();
}
}
return outInfos;
}
/**
* 执行命令附加超时时间
*
* @param command 命令
* @param timeoutSeconds 超时时间
* @return 执行结果
*/
public static List<String> executeWinCommandWaitTimeout(String command, long timeoutSeconds) {
if (StrUtil.isEmpty(command)) {
log.warn("the execute command is empty.");
return Collections.emptyList();
}
try {
return executeCommand("cmd /c " + command, timeoutSeconds);
} catch (Exception e) {
log.error("System execute command failed!", e);
}
return Collections.emptyList();
}
正文到此结束