z_s_l 2017-09-13 07:10 采纳率: 0%
浏览 2701

Jsch执行Shell脚本 发送回车,in.available()=0

public SshTest(String host, String user, String passwd) throws Exception {

    jsch = new JSch();
    session = jsch.getSession(user, host, 22);
    session.setPassword(passwd);
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setConfig("userauth.gssapi-with-mic", "no");
    session.setConfig("GSSAPIAuthentication", "no");
    session.connect(15000);
    channel = (ChannelShell) session.openChannel("shell");   
    ((ChannelShell)channel).setXForwarding(false);  
    ((ChannelShell)channel).setPty(false);          
    channel.setInputStream(null);
    channel.connect(15000);
    System.out.println("ssh通道创建成功");
}
public byte[] readEcho(String cmd) throws Exception {
    System.out.println("cmd:" + cmd);
    final PrintStream pstream = new PrintStream(channel.getOutputStream(), true);
    InputStream in = channel.getInputStream();
    byte[] data = new byte[] {};
    byte[] buf=new byte[1024];
    pstream.println("\r\n");         //发送空格
    pstream.flush();
    Thread.currentThread().sleep(1000l);
      while(true){
          int count = 0;
        while((count=in.available())>0){ //卡在这里 in.available()一直都是0,
          int len=in.read(buf, 0, 1024);
          if(len<0)break;
          System.out.print(new String(buf, 0, len));
           if (data.length == 0) {
                data = Arrays.copyOf(buf, len);
            } else {
                int tlen = len + data.length;
                byte[] tmp = new byte[tlen];
                System.arraycopy(data, 0, tmp, 0, data.length);
                System.arraycopy(buf, 0, tmp, data.length, len);
                data = tmp;
            }
        }
        if(channel.isClosed()){
          if(in.available()>0) continue;
          System.out.println("exit-status: "+channel.getExitStatus());
          break;
        }
        try{Thread.sleep(count==0?1000:100);}catch(Exception ee){}
      }
      in.close();
      pstream.close();
      channel.disconnect();
      session.disconnect();
    return data;
}
  • 写回答

1条回答 默认 最新

  • %九思% 2019-08-01 15:23
    关注

    增加其为0时,break应该就可以了

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog