项目场景:
需要用到jsch连接sftp,上传和下载文件
问题描述
jsch连接sftp出现 algorithm negotiation fail错误
原因分析:
客户端算法与服务端算法不一致导致的
解决方案:
方案一(现在网上大多数的方案)但这个方案并不能彻底解决我的问题。
修改sshd的配置文件 /etc/ssh/sshd_config
在配置文件中添加:
Ciphers aes128-cbc,aes192-cbc,aes256-cbc,aes128-ctr,aes192-ctr,aes256-ctr,3des-cbc,arcfour128,arcfour256,arcfour,blowfish-cbc,cast128-cbc
MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-sha1-96,hmac-md5-96
KexAlgorithms diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group1-sha1,curve25519-sha256@libssh.org
方案二 升级jsch的版本,我的版本0.1.55。
我添加了方案一和方案二后,已然出现algorithm negotiation fail错误。
通过查看 session.connect()方法里面com.jcraft.jsch.KeyExchange#getKeyAlgorithName方法
发现可以通过日志打印出客户端和服务端的算法,方法中的for会循环每一种算法进行匹配,如果找不到匹配的算法则会返回null,抛出异常algorithm negotiation fail
打印日志的代码
JSch.setLogger(new com.jcraft.jsch.Logger() {
@Override
public boolean isEnabled(int level) {
return true;
}
@Override
public void log(int level, String message) {
log.info("level:{},message:{}",level,message);
}
});
结果
从结果算法对比,可以看出是rsa算法不匹配导致的。
修改服务器配置文件sshd_config,加入客户端的算法,
ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
HostKeyAlgorithms ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
重启ssh解决算法不匹配连接问题。
后续遇到报错session is down。
权限问题,权限不要设置成777即可。
这个问题我也是百度了网上大多方法试过了都没用,最后只能看源码了,通过源码可以看到打印算法日志,对比算法逻辑。总结下来。只要把客户端的算法,配置到服务端就行了。