命令未在 Java 中解释

Command is Not Interpreting in Java

我有这个积木;

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("bash -c \"mkdir .typo && mkdir .typo/lib && mkdir src/ && mkdir bin/ && ln -sFf .typo/lib lib && mkdir .typo/runtime && touch src/main.typo && echo \"@include !main\n\ndef main(str[255] args) {\n    std:out(\"Hello, world!\");\n\n    return 0;\n}\n\" >> src/main.typo\"");

try {
    process.waitFor();
} catch (InterruptedException interruptedException) {
    System.exit(130);
}

当我执行它时,没有任何反应。它有时会发生,但大多数情况下它不起作用。我也检查了文件系统,也没有什么不同。

(InterruptedException 是用 import java.lang.InterruptedException 导入的。)

我试过了,错误是;

.typo: -c: line 0: unexpected EOF while looking for matching `"'
.typo: -c: line 1: syntax error: unexpected end of file

您需要查看 stderr 输出以诊断您的命令在做什么:

添加:

        InputStream is = process.getErrorStream();
        System.out.println(IOUtils.toString(is));

创建流程后。

IOUtils 来自:

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.8.0</version>
        </dependency>

当前输出为:

.typo: -c: line 0: unexpected EOF while looking for matching `"'
.typo: -c: line 1: syntax error: unexpected end of file

OWASP 一致,我这样做是为了帮助提高命令的可读性并检索它们的输出(一旦执行)。

public class SafeShellExecution {

    
    public String Execute(String[] command) {
        
        StringBuilder strAppend = new StringBuilder();
        
        try {
                String line;
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((line = in.readLine()) != null) {
                    strAppend.append(line);
                }
                in.close();
        } catch (IOException ex) {
            Logging.LogException(ex);
        }
        
        return strAppend.toString();
    }

}

然后干净利落地定义命令:

    public static final String[] GetIPAddress = {
        "/bin/sh",
        "-c",
        "ifconfig | grep -v '127.0.0.' | grep -i 'inet ' | awk {' print  '} | paste -sd ','"
    };

然后执行:

SafeShellExecution.Execute(GetIPAddress);