2012-08-27 41 views
4

我是JSch的新手,我尝试远程执行一些脚本时出现问题,而且似乎永远不会结束(并且与我运行时使用的方法不同油灰)。JSch:通道从未关闭或EOF

我已经重定向错误和输出流到我的System.out,并看到确实错误,当脚本执行,但脚本完成!因此我不明白为什么频道仍处于开放状态(isClosed和isEOF为假)。

当我用putty连接SSH时,脚本执行正确并且不显示任何错误。当我在Ubuntu中使用ssh命令执行ssh user @ host“my command”命令时,我得到与使用JSch时相同的输出(std + err),但ssh命令没有挂起!

你知道我做错了什么,为什么我有不同的输出/行为?这里是我运行的java代码(顺便说一句,我不能在同一个会话中用不同的通道发送几个命令,我不知道为什么,因此我为每个cmd打开一个会话)。

public static void runCommand(String user, String password, String cmd) throws JSchException, IOException{ 
    Session session = jSsh.getSession(user, SERVER, SSH_PORT); 
    session.setPassword(password); 
    session.setConfig(SSH_PROPERTIES); 
    session.connect(); 
    SshCommand sshCmd = new SshCommand(session, cmd); 
    runCommand(sshCmd); 
    session.disconnect(); 
} 

private static void runCommand(SshCommand sshCmd) throws IOException, JSchException{ 

    Session session = sshCmd.getSshSession(); 
    String cmd = sshCmd.getCmd(); 


    UtilityLogger.log(Level.FINE, "Running command on ssh : "+cmd); 

    ChannelExec channel = (ChannelExec) session.openChannel("exec"); 
    channel.setCommand(cmd); 
    channel.setInputStream(null); 

    InputStream in = channel.getInputStream(); 
    InputStream err = channel.getErrStream(); 
    UtilityLogger.log(Level.FINEST, "Connecting to channel"); 
    channel.connect(); 
    UtilityLogger.log(Level.FINEST, "Channel connected"); 

    byte[] tmp = new byte[1024]; 
      byte[] tmp2 = new byte[1024]; 
    while (true) { 
     //Flush channel 
     while (in.available() > 0) { 
      int i = in.read(tmp, 0, 1024); 
      if (i < 0) 
       break; 
      UtilityLogger.log(Level.FINE, new String(tmp, 0, i)); 
     } 
     //Flush Error stream 
     while (err.available() > 0) { 
      int i = err.read(tmp2, 0, 1024); 
      if (i < 0) 
       break; 
      UtilityLogger.log(Level.FINE, new String(tmp2, 0, i)); 
     } 
     if(DONT_WAIT_PROCESS_END) 
      break; 
     if (channel.isEOF()) { 
      UtilityLogger.log(Level.FINE, "Channel exit-status: " + channel.getExitStatus()); 
      break; 
     } 
    } 
    try{Thread.sleep(TIME_BETWEEN_COMMAND);}catch(Exception ee){} 
    channel.disconnect(); 
    UtilityLogger.log(Level.FINEST, "Channel disconnected"); 
} 
+1

不知道有人吗? – Abbadon

+0

如果in.available()<= 0和channel.isEOF()== false,会发生什么情况?可能是无限循环问题。 – oers

回答

2

尝试追加“exit”甚至在使用exec频道时也可以在您的命令后进行。