萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Java 執行 Shell 腳本完整指南:Runtime.exec、ProcessBuilder、超時控制、輸出處理

核心 API 比較

API優點缺點推薦場景
Runtime.getRuntime().exec()簡單、舊版相容參數處理麻煩、無建構者模式、錯誤流需手動讀取簡單單一指令
ProcessBuilder參數列表型安全、支援目錄/環境變數/管道、可重導向輸出API 較繁瑣複雜指令、生產環境
Apache Commons Exec超時、監看、結果處理器、依賴管理第三方依賴企業級應用

ProcessBuilder 完整封裝工具類 (推薦)

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;

public class ShellExecutor {
  private static final int DEFAULT_TIMEOUT_SEC = 30;
  private static final int BUFFER_SIZE = 8192;

  public static class Result {
    public final int exitCode;
    public final String stdout;
    public final String stderr;
    public final boolean timedOut;
    public final long durationMs;

    private Result(int exitCode, String stdout, String stderr, boolean timedOut, long durationMs) {
      this.exitCode = exitCode;
      this.stdout = stdout;
      this.stderr = stderr;
      this.timedOut = timedOut;
      this.durationMs = durationMs;
    }

    public boolean isSuccess() { return exitCode == 0 && !timedOut; }
    
    @Override public String toString() {
      return String.format("Result[exit=%d, timeout=%b, duration=%dms, stdout=%d chars, stderr=%d chars]",
        exitCode, timedOut, durationMs, stdout.length(), stderr.length());
    }
  }

  public static Result execute(List command) {
    return execute(command, DEFAULT_TIMEOUT_SEC);
  }

  public static Result execute(List command, int timeoutSeconds) {
    return execute(command, timeoutSeconds, null, null);
  }

  public static Result execute(List command, int timeoutSeconds, 
                               Map env, File workingDir) {
    long start = System.currentTimeMillis();
    ProcessBuilder pb = new ProcessBuilder(command);
    
    if (env != null) pb.environment().putAll(env);
    if (workingDir != null) pb.directory(workingDir);
    
    // 合併錯誤流到標準輸出 (避免雙緩衝區死鎖)
    pb.redirectErrorStream(true);
    
    try {
      Process process = pb.start();
      
      // 非同步讀取輸出
      StringBuilder output = new StringBuilder();
      try (BufferedReader reader = new BufferedReader(
           new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8), BUFFER_SIZE)) {
        
        String line;
        while ((line = reader.readLine()) != null) {
          output.append(line).append('\n');
        }
      }
      
      // 等待結束或超時
      boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
      long duration = System.currentTimeMillis() - start;
      
      if (!finished) {
        process.destroyForcibly().waitFor(1, TimeUnit.SECONDS);
        return new Result(-1, output.toString(), "Timeout after " + timeoutSeconds + "s", true, duration);
      }
      
      return new Result(process.exitValue(), output.toString(), "", false, duration);
      
    } catch (IOException | InterruptedException e) {
      Thread.currentThread().interrupt(); // 保留中斷狀態
      return new Result(-1, "", e.getMessage(), false, System.currentTimeMillis() - start);
    }
  }

  // 便利方法:字串指令自動分割 (簡單場景)
  public static Result execute(String command, int timeoutSeconds) {
    return execute(Arrays.asList(command.split("\\s+")), timeoutSeconds);
  }
}

使用範例

public class Demo {
  public static void main(String[] args) {
    // 1. 簡單指令
    Result r1 = ShellExecutor.execute("ls -la /tmp");
    System.out.println(r1);
    System.out.println(r1.stdout);

    // 2. 複雜指令含參數 (避免空格分割問題)
    Result r2 = ShellExecutor.execute(Arrays.asList(
      "find", "/var/log", "-name", "*.log", "-mtime", "-7"
    ), 60);
    System.out.println(r2);

    // 3. 環境變數與工作目錄
    Map env = new HashMap<>();
    env.put("CUSTOM_VAR", "test123");
    Result r3 = ShellExecutor.execute(Arrays.asList("bash", "-c", "echo $CUSTOM_VAR"), 
                                      10, env, new File("/tmp"));
    System.out.println(r3.stdout.trim()); // test123

    // 4. 管道指令 (需 shell 解析)
    Result r4 = ShellExecutor.execute(Arrays.asList("bash", "-c", "ps aux | grep java | head -5"), 10);
    System.out.println(r4.stdout);
  }
}

進階:即時輸出處理 (Streaming)

public static void executeStreaming(List command, 
                                    Consumer stdoutHandler,
                                    Consumer stderrHandler,
                                    int timeoutSeconds) throws IOException, InterruptedException {
  ProcessBuilder pb = new ProcessBuilder(command);
  pb.redirectErrorStream(false); // 分離 stdout/stderr
  Process process = pb.start();

  ExecutorService executor = Executors.newFixedThreadPool(2);
  
  Future stdoutFuture = executor.submit(() -> {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
      String line;
      while ((line = br.readLine()) != null) stdoutHandler.accept(line);
    }
  });
  
  Future stderrFuture = executor.submit(() -> {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
      String line;
      while ((line = br.readLine()) != null) stderrHandler.accept(line);
    }
  });

  try {
    boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
    if (!finished) process.destroyForcibly();
  } finally {
    executor.shutdownNow();
    try { executor.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException ignored) {}
  }
}

// 使用:即時顯示建構日誌
ShellExecutor.executeStreaming(
  Arrays.asList("./gradlew", "build"),
  line -> System.out.println("[OUT] " + line),
  line -> System.err.println("[ERR] " + line),
  300
);

常見坑點與解決

  1. 雙緩衝區死鎖:stdout/stderr 緩衝區滿時進程阻塞
    • 解決:pb.redirectErrorStream(true) 合併流,或啟動兩執行緒同時讀取
  2. 參數含空格/特殊字元:字串 split 失效
    • 解決:使用 List 逐個參數傳遞,或 bash -c "cmd"
  3. Windows 路徑反斜線
    • 解決:Java 字串雙重跳脫 C:\\\\path 或用正斜線 C:/path
  4. 權限不足
    • 解決:確保執行使用者有權限,或用 sudo (需免密設定)
  5. 環境變數未生效
    • 解決:pb.environment() 只影響子進程,不影響 JVM

安全性警示

  • 命令注入風險:絕不拼接使用者輸入到指令字串,務必使用 List 參數化
  • 最小權限原則:執行腳本的系統用戶應為非 root、權限最小化
  • 審計日誌:記錄執行指令、參數、使用者、時間、結果

總結

Java 執行 Shell 腳本首選 ProcessBuilder,封裝工具類統一處理超時、編碼、雙流讀取、錯誤處理。複雜場景引入 Apache Commons Exec。嚴防命令注入,生產環境務必審計記錄。

copyright © 萬盛學電腦網 all rights reserved