我有方法使用j2ssh sshclient在Linux服務器上執行遠程命令。遠程命令可以從幾秒到幾分鐘之內執行。我需要Java程序等待命令完成執行後才能繼續,但事實並非如此。 Java程序運行該命令,但在遠程命令完成之前繼續運行。這裏是我的方法:j2ssh sshclient不等待遠程命令來完成
//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;
}