2 z s l z_s_l 于 2017.09.13 15:10 提问

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;
}
Csdn user default icon
上传中...
上传图片
插入图片