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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With