我有一个使用在j2ssh服务器上执行远程命令的方法。执行远程命令可能需要几秒钟到一分钟以上的时间。我需要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;
}发布于 2015-07-20 18:47:38
这里的问题是,您启动shell,输出命令,然后线程化读取操作,因此从Inputstream读取是在另一个线程上执行的。您的函数的主线程立即移动到关闭会话,因此您的命令将在收到所有输出之前被终止。
为了防止这种情况,只需从会话的输入流中读取,直到它在同一线程上返回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);
}发布于 2016-04-07 16:12:37
它应该以如下方式工作:
//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();
if ( session.executeCommand(cmd) ) {
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos);
String theOutput = bos.toString();
System.out.println("output..." + theOutput);
}
session.close();https://stackoverflow.com/questions/30486890
复制相似问题