首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >j2ssh sshclient不等待远程命令完成

j2ssh sshclient不等待远程命令完成
EN

Stack Overflow用户
提问于 2015-05-27 23:30:15
回答 2查看 1.2K关注 0票数 0

我有一个使用在j2ssh服务器上执行远程命令的方法。执行远程命令可能需要几秒钟到一分钟以上的时间。我需要Java程序等到命令执行完成后再继续执行,但它没有,Java程序运行命令,但在远程命令结束之前继续运行。下面是我的方法:

代码语言:javascript
复制
//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;

  }
EN

回答 2

Stack Overflow用户

发布于 2015-07-20 18:47:38

这里的问题是,您启动shell,输出命令,然后线程化读取操作,因此从Inputstream读取是在另一个线程上执行的。您的函数的主线程立即移动到关闭会话,因此您的命令将在收到所有输出之前被终止。

为了防止这种情况,只需从会话的输入流中读取,直到它在同一线程上返回EOF,即删除使用IOStreamConnector并手动读取到您的ByteArrayOutputStream中。然后,一旦流返回EOF,就调用session.close(),因为这表示已经从服务器接收到所有数据。

代码语言:javascript
复制
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);
}
票数 1
EN

Stack Overflow用户

发布于 2016-04-07 16:12:37

它应该以如下方式工作:

代码语言:javascript
复制
//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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30486890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档