← 中文资源

简体中文版本

ProcessBuilder 参数列表安全执行

用 ProcessBuilder 参数列表执行外部命令:不经 shell 解析、合并错误流、硬超时后 destroyForcibly 清理。

阅读英文原文

实现说明

ProcessBuilder 参数列表安全执行的核心是类 SafeCommand。 非法状态在入口就被拒绝:抛出 IllegalStateException,而不是带着坏数据继续。

使用要点

  • 直接运行文件,输出会带上标签,比如 exit=——输出的每一行都能指回产生它的那次调用。

常见问题

输入非法时会怎样?

在真正开工之前就会抛出 IllegalStateException——请在调用点处理,或有意向上传播。

运行「ProcessBuilder 参数列表安全执行」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 exit= 这类标签。

核心语句

throw new IllegalStateException("command timed out: " + command.get(0));

代码示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SafeCommand {

    public static void main(String[] args) throws Exception {
        Path workdir = Files.createTempDirectory("safe-cmd");

        // 参数以 List 传递:不经 shell 解析,用户输入无法注入额外命令
        List<String> command = List.of("git", "-C", workdir.toString(), "init", "--quiet");

        Process process = new ProcessBuilder(command)
                .redirectErrorStream(true)
                .directory(workdir.toFile())
                .start();

        boolean finished = process.waitFor(10, TimeUnit.SECONDS);
        if (!finished) {
            process.destroyForcibly();
            process.waitFor();
            throw new IllegalStateException("command timed out: " + command.get(0));
        }

        String output = new String(process.getInputStream().readAllBytes());
        System.out.println("exit=" + process.exitValue());
        if (!output.isBlank()) {
            System.out.println(output.strip());
        }
    }
}