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)

3
  • 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 stackoverflow.com/questions/1677248/simple-ssh-tunnel-in-java Commented Jul 4, 2012 at 15:39
  • ...and by the way, since Java 5 the preferred way to do this is by using ProcessBuilder class (docs.oracle.com/javase/1.5.0/docs/api/java/lang/…) Commented Jul 4, 2012 at 15:56
  • ohhh good idea ^^ i just used the code because my predecessor also did but an extra library sounds better Commented Jul 4, 2012 at 15:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i will try the ssh libraries. Thanks for the fast answer ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.