【问题标题】:JSch - How to capture stream from remote server using PortForwarding L?JSch - 如何使用 PortForwarding L 从远程服务器捕获流?
【发布时间】:2019-01-05 02:28:48
【问题描述】:

我尝试使用 InputStream 和 Buffer[],还有 BufferedReader,还有 PipedInputStream。对于所有情况,我都为空:

        sessionB = jSch.getSession(username, "localhost", forwardedPort);
        sessionB.connect();

          if(sessionB.isConnected()) {
             System.out.println("Connected host B!");

             channel = (ChannelExec) sessionB.openChannel("exec");   

             br = new BufferedReader(new 
             InputStreamReader(channel.getInputStream())); 
             ((ChannelExec)channel).setCommand("command");
             ((ChannelExec)channel).setErrStream(System.err);

             channel.connect();

             if(channel.isConnected()) {

                System.out.println("Channel is connected!");
            }

             String line;

                    while((line = br.readLine()) != null) {
                    System.out.println(line);
                    }

和控制台输出:

已连接主机 A!已连接主机 B!频道已连接!

问题:我没有打印任何东西 (System.out.println(line);)

有没有办法通过端口转发从 exec 通道获取该流?感谢您的帮助

【问题讨论】:

  • 您的代码对我来说工作得很好,假设您没有向我们展示的其余代码是合理的。我们需要minimal reproducible example

标签: java jsch portforwarding bufferedinputstream


【解决方案1】:

感谢您的帮助。我使用 Pipes 解决了它,我分享了我所做的:

  PipedInputStream en = new PipedInputStream();
  pin = new PipedOutputStream((PipedInputStream) en);
  BufferedReader br = new BufferedReader(new InputStreamReader((PipedInputStream) 
  channel.getInputStream()));

  channel.connect(5*1000);     


  String received=null;
  while((received=br.readLine())!=null) {
      System.out.println(received);
  }

【讨论】:

  • 我仍然没有得到你的代码。从我读到你的变量'pin'没有被使用,你所做的只是用缓冲的阅读器收集你的命令输出。
  • 我认为在 PipedInputStream 中转换 channel.getInputStream() 是没用的。
  • 第一个缓冲区输入,然后读取如下: StringBuilder sb = new StringBuilder(); while((received=br.readLine())!=null) {sb.append(received+"\n"); // 我同意你的观点,但是没有那个转换就会标记一个错误
【解决方案2】:

get/setInputStream 和get/setOutputStream 只关注命令的标准输入/输出,与端口转发无关。 端口转发是通过两个函数 setPortForwardingL 和 setPortForwardingR 完成的。

你的代码中应该有类似的东西。

int assinged_port=session.setPortForwardingL(lport, rhost, rport);

与往常一样,关于 JSCH 的文档很少,但有很多 detailed examples 用于 L forwardingR forwarding

端口转发是在会话中完成的,所以我不确定您是否还需要一个活动连接。但是如果你这样做了,你应该考虑打开一个“shell”连接而不是一个“exec”。这样您就不必为了维持连接而运行无用的命令。

PS:缺少一些代码,因此很难在问题中给出的示例中说出准确的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    相关资源
    最近更新 更多