Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

com.jcraft.jsch.JSchException: channel is not opened when opening a channel in jsch

Tags:

java

jsch

When connecting to a remote host using jsch version 0.1.51 we occasionally run into the following exception when calling Channel.connect() on a ChannelExec.

com.jcraft.jsch.JSchException: channel is not opened.
    at com.jcraft.jsch.Channel.sendChannelOpen(Channel.java:765)
    at com.jcraft.jsch.Channel.connect(Channel.java:151)
    at com.jcraft.jsch.Channel.connect(Channel.java:145)

The code we use after the session has been created is:

ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("echo hello");
channel.connect(); // Error here

The Channel.connect() call usually returns in under 100 ms, but when this error ocurrs the call hangs for more than 20 seconds before throwing the exception.

like image 482
K Erlandsson Avatar asked Nov 24 '15 13:11

K Erlandsson


1 Answers

The exception message is slightly misleading. The error can occur when there is a timeout waiting for the SSH_MSG_CHANNEL_OPEN_CONFIRMATION message from the server. The default timeout in jsch (version 0.1.51) is 20 seconds. I think there are other situations where the same error occurrs but I have not investigated further.

While there probably can be numerous reasons for the timeout, we have seen it caused by reverse DNS lookups in sshd from OpenSSH that took a long time occasionally.

That cause can be resolved by disabling DNS lookups from sshd by setting

UseDNS no

in your sshd_config (typically /etc/ssh/sshd_config). This is generally safe to do according to what Gilles writes in this thread.

Another option is to increase the timeout when connecting the channel. Channel.connect accepts a timeout argument (milliseconds), e.g. channel.connect(60000). This can be useful if you do not control the server you are connecting to.

like image 158
K Erlandsson Avatar answered Nov 08 '22 15:11

K Erlandsson