当使用 jsch 版本 0.1.51 连接到远程主机时,我们偶尔会在 ChannelExec
上调用 Channel.connect()
时遇到以下异常。
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)
创建 session 后我们使用的代码是:
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("echo hello");
channel.connect(); // Error here
Channel.connect()
调用通常会在 100 毫秒内返回,但是当发生此错误时,调用会在抛出异常之前挂起超过 20 秒。
最佳答案
异常消息有点误导。当等待来自服务器的 SSH_MSG_CHANNEL_OPEN_CONFIRMATION
消息超时时,可能会发生该错误。 jsch(版本 0.1.51)中的默认超时为 20 秒。我认为还有其他情况会发生相同的错误,但我没有进一步调查。
虽然超时的原因可能有很多,但我们已经看到它是由 OpenSSH 中的 sshd 中的反向 DNS 查找偶尔花费很长时间引起的。
可以通过设置
禁用来自 sshd 的 DNS 查找来解决这个问题UseDNS no
在您的 sshd_config 中(通常是 /etc/ssh/sshd_config
)。根据 Gilles 在 this 中所写,这通常是安全的线程。
另一种选择是增加连接 channel 时的超时时间。 Channel.connect
接受超时参数(毫秒),例如channel.connect(60000)
。如果您不控制要连接的服务器,这会很有用。
关于java - com.jcraft.jsch.JSchException : channel is not opened when opening a channel in jsch 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895500/