没有输入时,通道不会自行关闭。阅读完所有数据后,请尝试自己关闭它。
while (true) { while (inputStream.available() > 0) { int i = inputStream.read(buffer, 0, 1024); if (i < 0) { break; } System.out.print(new String(buffer, 0, i));//It is printing the response to console } System.out.println("done"); channel.close(); // this closes the jsch channel if (channel.isClosed()) { System.out.println("exit-status: " + channel.getExitStatus()); break; } try{Thread.sleep(1000);}catch(Exception ee){}}您唯一要使用不会手动关闭通道的循环是在您收到用户的交互式键盘输入时。然后,当用户执行“退出”操作时,该操作将更改通道的“
getExitStatus”。如果您的循环为while(channel.getExitStatus()== -1),则当用户退出时循环将退出。
在检测到退出状态后,您仍然需要断开通道并自己进行会话 。
它没有在示例页面上列出,但是JSCH在其站点上托管了一个交互式键盘演示。
http://www.jcraft.com/jsch/examples/UserAuthKI.java
即使是我的演示程序,我用来连接到AIX系统而不更改任何代码的演示程序,在退出Shell时也不会关闭!
在远程会话中键入“退出”后,我必须添加以下代码才能使其正确退出:
channel.connect(); // My added pre begins here while (channel.getExitStatus() == -1){ try{Thread.sleep(1000);}catch(Exception e){System.out.println(e);} } channel.disconnect(); session.disconnect(); // My Added pre ends here } catch(Exception e){ System.out.println(e); }}


