我有使用 j2ssh sshclient 在 linux 服务器上执行远程命令的方法。执行远程命令可能需要几秒钟到一分钟多的时间。我需要 Java 程序等到命令完成执行后再继续,但事实并非如此。 Java 程序运行该命令,但随后在远程命令完成之前继续运行。这是我的方法:
//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;
}
最佳答案
这里的问题是您启动 shell,输出您的命令,然后关闭读取操作,因此从 Inputstream 读取是在另一个线程上执行的。您的函数的主线程立即移动到关闭 session ,因此您的命令将在收到所有输出之前被终止。
为了防止这种情况,只需从 session 的输入流中读取直到它在同一线程上返回 EOF,即删除 IOStreamConnector 的使用并手动读入您的 ByteArrayOutputStream。然后在流返回 EOF 后调用 session.close(),因为这表示已从服务器接收到所有数据。
byte[] buf = new byte[1024];
int r;
ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
while((r = session.getInputStream().read(buf)) > -1) {
bos.write(buf, 0, r);
}
关于java - j2ssh sshclient 不等待远程命令完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30486890/