Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running commands over ssh with Java

Tags:

java

ssh

openssh

Scenerio: I'd like to run commands on remote machines from a Java program over ssh (I am using OpenSSH on my development machine). I'd also like to make the ssh connection by passing the password rather than setting up keys as I would with 'expect'.
Problem: When trying to do the 'expect' like password login the Process that is created with ProcessBuilder cannot seem to see the password prompt. When running regular non-ssh commands (e.g 'ls') I can get the streams and interact with them just fine. I am combining standard error and standard out into one stream with redirectErrorStream(true); so I am not missing it in standard error...When I run ssh with the '-v' option, I see all of the logging in the stream but I do not see the prompt. This is my first time trying to use ProcessBuilder for something like this. I know it would be easier to use Python, Perl or good ol' expect but my boss wants to utilize what we are trying to get back (remote log files and running scripts) within an existing Java program so I am kind of stuck.

Thanks in advance for the help!

like image 303
Ichorus Avatar asked Feb 20 '09 17:02

Ichorus


2 Answers

The prompt might only be shown when ssh is connected to a TTY, which it isn't in the case of Java.

There's probably a way to supply the password on the command-line in your ssh application. That will be the way to get past the prompt.

Alternately, consider connecting directly to the host server from native Java code rather than running an external application. There's a million libraries that will do this.

like image 120
Jason Cohen Avatar answered Oct 25 '22 23:10

Jason Cohen


Rather than using an external ssh program, why not use a Java ssh library:

  • Trilead
  • JTA

Are two I found with google - that'll avoid the problem that openssh will be working very hard to prevent entering the password on stdin - it'll be opening the terminal directly. expect has to work very hard to simulate a tty in order to work.

like image 45
Douglas Leeder Avatar answered Oct 25 '22 23:10

Douglas Leeder