2

I would like to know how to create a file / directory in remote machine using Java11 ?

I did try to use:

process = Runtime.getRuntime()
         .exec("ssh root@" + hostname + " 'mkdir -p "+mdbDir+"'")
         .wait() or waitFor();

But i am getting an exception even though i use wait()

java.lang.IllegalThreadStateException: process has not exited

Please let me know what can be done.

Vijay
  • 1,026
  • 3
  • 11
  • 28
  • 1
    You probably have to read command's output to see what happened. – Antoniossss Dec 04 '19 at 07:12
  • @antoniossss you can help me reading if you know. – Vijay Dec 04 '19 at 07:17
  • 1
    Note that there are Java SSH implementations out there as well. I never like executing an external application. – Maarten Bodewes Dec 04 '19 at 07:24
  • 2
    [`wait`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--) and [`waitFor`](https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html#waitFor--) are entirely different methods with an entirely different purpose. You should never mix them up. And since you didn’t notice the `IllegalMonitorStateException` when calling `wait` without synchronization, you must have some sort of “catch all and ignore” construct in your code. Another thing you should never do. – Holger Dec 04 '19 at 09:51
  • @Holger Thank you i dint use both together wait and waitFor . – Vijay Dec 05 '19 at 03:46
  • You shouldn’t use `wait` at all, neither together with `waitFor` nor alone. The method `wait` is just wrong here. – Holger Dec 05 '19 at 07:33

2 Answers2

1

You should only call Process.waitFor() without Process.wait(). Object.wait is about synchronization. It has nothing to do with process management.

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
-1

You have a good example here about how to use an SSHClient from sshj, more specific for the task that you want to do:

Send ssh command from Java code

Moreover, you will probably need a trusted connection with the target server. Check if an SSH connection from your system requires a password, if your system and the server has a trusted connection it will no ask for the password.

If you still want to use your approach without a library I guess that the problem is that the execution is waiting for some input like adding the host to the knowhosts or the password, and that is the reason for the process not exiting.

Juan Franco
  • 199
  • 1
  • 7