The channel does not close itself when there is no input left. Try closing it yourself after you have read all data.
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){}
}
The only time you are going to use a loop that doesnt manually close the channel is when you have interactive keyboard input from the user. Then when the user does an 'exit' that will change the channel's 'getExitStatus'. If your loop is while(channel.getExitStatus() == -1) then the loop will exit when the user has exited. You still need to disconnect the channel and session yourself after you detect an Exit Status.
It is not listed on their example page, but JSCH hosts an interactive keyboard demo on their site. http://www.jcraft.com/jsch/examples/UserAuthKI.java
Even their demo, which I used to connect to an AIX system without changing any of their code... does not close when you exit the shell!
I had to add the following code to get it to exit properly after I had typed 'exit' in my remote session:
channel.connect();
// My added code begins here
while (channel.getExitStatus() == -1){
try{Thread.sleep(1000);}catch(Exception e){System.out.println(e);}
}
channel.disconnect();
session.disconnect();
// My Added code ends here
}
catch(Exception e){
System.out.println(e);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…