JSch: Channel is never closed or EOF

I am new to JSch and I have a problem with some of my script. I am trying to execute remotely and it seems to never end (and does not do the same as when I started using putty).

I redirected the error and the output stream to my System.out and really see the error while executing the script, but the script completed! Therefore, I do not understand why the channel is still open (isClosed and isEOF are false).

When I run the command when connecting to SSH using putty, the script is executed correctly and does not show any errors. When I do ssh user @host "my command" using the ssh command in Ubuntu, I get the same output (std + err) as when using JSch, but the ssh command does not hang!

Do you have any idea what I'm doing wrong, why do I have different results / behavior? Here is the java code that I am running (by the way, I CAN’t send several commands with a different channel in the same sessions, and I don’t know why, so I open one session for each 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"); } 
+4
source share
2 answers

Try adding "exit"; after your commands even when using exec channels.

+2
source

Our application also did not receive EOF. Adding exit; so that the team does not solve the problem.

This has something to do with stderr output. Redirecting stderr to stdout solved the problem (workaround ?!).
So, we added 2>&1 to the command:

 ${command} 2>&1 
0
source

All Articles