1

I have a shell script that I would like to execute from java.

sudo su - username -c "ssh -t remote_hostname df -k"

This shell script works fine when you ran from the command prompt. However when I used process builder it will not return anything. If I do the following: sudo su - username -c ssh -t remote_hostname;df -k

then the command is running on my local machine not on the remote machine.

Appreciated any feedback.


java code

Process p;

ExecutorService es = null;
try {

p = Runtime.getRuntime().exec(test1.sh);

StreamGobbler sg = new StreamGobbler(p.getInputStream(), System.out::println());

es = Executors.newSingleThreadExecutor();

es.submt(sg);

int exitCode = p.waitfor();

assert exitCode == 0;

es.shutdown();


} catch (....) {
}
Roberto Manfreda
  • 2,345
  • 3
  • 25
  • 39

1 Answers1

1

Runtime.exec(String) is not a shell, and in particular doesn't parse and handle quotes like a shell. Dupe:
Why does Runtime.exec(String) work for some but not all commands?
Whitespace in bash path with java
Keytool command does not work when invoked with Java

Do something like

String[] cmd = { "sudo", "su", "-", "username", "-c", "ssh -t remote_hostname df -k" };
// note the last element is a single Java String that does not _contain_ 
// any quote characters (which would be backslashed in Java source)
... Runtime.getRuntime().exec(cmd) ...

Also, you shouldn't need -t when remoting df -k -- it doesn't do any special output handling. (Although it doesn't hurt, and is nearly free.)

dave_thompson_085
  • 34,712
  • 6
  • 50
  • 70
  • Thank you so much, the above solution works. I appreciated very much for the answer as I have spent a week trying to figure out why it will not work in Java. – Lucia Sugianto Nov 26 '19 at 14:32
  • Yes Dave you are right... I removed my response because was a totally wrong content... Anyway this topic moved some interest in me so i started writing some code... I think that this side of java can be improved writing some good library! Tonight I started writing a library to execute entire scripts from java code using the exec() method. If you are interested contributing here's the github link https://github.com/robertomanfreda/java_bash_executor . The workaround i used is: read a file line after line, encode the content in base64 and execute the encoded content on /bin/bash using base64 :) – Roberto Manfreda Nov 26 '19 at 15:29