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

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 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊