I have method that uses j2ssh sshclient to execute a remote command on a linux server. The remote command can take anywhere from a few seconds to over a minute to execute. I need the Java program to wait until the command is finished executing before proceeding, but it doesn't. The Java program runs the command but then continues before the remote command finishes. Here's my method:
//The connect is done prior to calling the method.
public static String executeCommand(String host, String command, String path)
throws Exception
{
cd(path);
System.out.println("-- ssh: executing command: " + command + " on "
+ host);
SessionChannelClient session = ssh.openSessionChannel();
session.startShell();
session.getOutputStream().write("sudo -s \n".getBytes());
session.getOutputStream().write(command.getBytes());
session.getOutputStream().write("\n exit\n".getBytes());
IOStreamConnector output = new IOStreamConnector();
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos);
String theOutput = bos.toString();
System.out.println("output..." + theOutput);
session.close();
disconnect();
return theOutput;
}