1

I am trying to run commands/executables in a remote host through a Java program. Here is the code I got from a related thread. I CAN connect to the remote host and read the stream through the BufferedReader in. However, I am NOT able to send/execute commands using out.println("ls /home/ubuntu");. Do you have any recommendations? I am working on a MAC OS system.

Process p = Runtime.exec("ssh myhost");
PrintStream out = new PrintStream(p.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream());
Thread.sleep(3000);
while (in.ready()) {
   String s = in.readLine();
   System.out.println(s);
}

out.println("ls /home/ubuntu");
Thread.sleep(3000);
while (in.ready()) {
    String s = in.readLine();
    System.out.println(s);
}
out.println("exit");

2 Answers 2

5

Got it to work.

PrintStream out = new PrintStream(p.getOutputStream());

does not work for me so I changed it to this.

PrintWriter out = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
Sign up to request clarification or add additional context in comments.

Comments

2

I had used a library JSch, but I guess sshxcute looks better as I went through the documentation.

Comments

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.