0

I have a short question concerning the Runtime.getRuntime.exec("") command in java.

I am trying to make a tunnel to a gateway computer via SSH:

String tunnel = "C:\\Program Files\\PuTTY\\putty.exe -ssh -X -P " + localPort + " " + tempUsername + "@" + localIP
                    + " -pw " + tempPassword + " -L " + tunnelPort + ":" + gatewayName + ":"+gatewayPort;

Runtime.getRuntime().exec(tunnel);

This bit of code works properly except the annoying fact that a command prompt appears.

Now I tried to exit the prompt after executing the code:

String tunnel = "C:\\Program Files\\PuTTY\\putty.exe -ssh -X -P " + localPort + " " + tempUsername + "@" + localIP
                    + " -pw " + tempPassword + " -L " + tunnelPort + ":" + gatewayName + ":"+gatewayPort;

String cmdCommands [] = {tunnel, "exit"};

Runtime.getRuntime().exec(cmdCommands);

Is it possible to close the command prompt in a similar way like I do or are there better ways? (This code doesnt work)

Mister004
  • 303
  • 1
  • 3
  • 10
  • Your code is just launching an executable (putty.exe). The command prompt you are seeing is putty. If you want to create an SSH tunnel, you have to use proper libraries, please see this thread http://stackoverflow.com/questions/1677248/simple-ssh-tunnel-in-java – sperumal Jul 04 '12 at 15:39
  • ...and by the way, since Java 5 the preferred way to do this is by using `ProcessBuilder` class (http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html) – mazaneicha Jul 04 '12 at 15:56
  • ohhh good idea ^^ i just used the code because my predecessor also did but an extra library sounds better – Mister004 Jul 04 '12 at 15:58

1 Answers1

1

You'll need to either use an actual SSH library directly instead of putty, as in the comments, or capture the IO streams of the exec

Process p = Runtime.getRuntime().exec(cmdCommands);
InputStream is = p.getInputStream();
OutputStream os = p.getOutputStream();
os.write("exit\n");

It's generally a bad idea to hard code \n, for platform reasons, but you get the idea. Also, you will need to pick the right OutputStream. There are several subclasses(buffered etc.) which may be useful.

Thomas
  • 5,074
  • 1
  • 16
  • 12