16

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.

K Erlandsson
  • 13,408
  • 6
  • 51
  • 67

1 Answers1

22

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.

Community
  • 1
  • 1
K Erlandsson
  • 13,408
  • 6
  • 51
  • 67
  • Good point with the time unit, in my case I had specified the timeout in seconds instead of milliseconds. – kelunik Aug 31 '22 at 07:52