sftp连接失败的解决方案:
- 服务器端的ssh版本升级到OpenSSH_8.4p1后,程序连接sftp异常,错误如下:
com.jcraft.jsch.JSchException: Session.connect: java.io.IOException: End of IO Stream Read - 查看服务器端的/etc/ssh/sshd_config文件如下:
KexAlgorithms +diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1 - 参考各种帖子,修改过程如下:
- 第一次修改
config.put("kex", "diffie-hellman-group1-sha1")
错误提示如下:com.jcraft.jsch.JSchException: Algorithm negotiation fail - 第二次修改
config.put("kex", "diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1"
+ ",diffie-hellman-group-exchange-sha256");
成功解决问题。工具类如下:
public SftpClientUtil(String host, String username, String password, int port) throws Exception {
JSch jsch = new JSch();
this.session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
config.put("kex", "diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1,"
+ "diffie-hellman-group-exchange-sha256");
session.setConfig(config);
try {
session.connect();
} catch (Exception e) {
if (session.isConnected())
session.disconnect();
logger.error("链接报错!!!",e);
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port
+ "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
channel = session.openChannel("sftp");
try {
if (channel.isConnected())
channel.disconnect();
channel.connect();
} catch (Exception e) {
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port
+ "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
sftp = (ChannelSftp) channel;
}