解决java客户端连接ssh失败问题
的运维工具使用了java的ssh客户端这些客户端和服务端间有时会出现加密算法协商失败和主机密钥类型协商失败的问题该问题是由于新客户端/服务端禁用了相关的不安全算法和密钥类型本文简要记录下该问题的解决方法以备不时之需。错误常见提示如下#加密算法协商失败Unable to negotiate with 192.168.56.99 port 54234: no matching key exchange method found. Their offer: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 [preauth]#主机密钥类型协商失败Unable to negotiate with 192.168.56.99 port 22: no matching host key type found. Their offer: ssh-rsa,ssh-dss [preauth]解决方法二选一较新的客户端兼容旧服务端以Jsch为例升级新版本。dependencygroupIdcom.jcraft/groupIdartifactIdjsch/artifactIdversion0.1.55/version !-- 检查最新版本 --/dependency代码中配置连接属性import com.jcraft.jsch.*;public class SSHConnector {public static void main(String[] args) {try {JSch jsch new JSch();// 设置支持的算法java.util.Properties config new java.util.Properties();// 关键配置指定算法config.put(kex, diffie-hellman-group1-sha1,diffie-hellman-group14-sha1);config.put(server_host_key, ssh-rsa,ssh-dss);config.put(cipher.s2c, aes128-ctr,aes128-cbc,3des-cbc);config.put(cipher.c2s, aes128-ctr,aes128-cbc,3des-cbc);config.put(mac.s2c, hmac-sha1);config.put(mac.c2s, hmac-sha1);Session session jsch.getSession(username, 172.16.29.254, 22);session.setConfig(config);session.setPassword(password);session.setConfig(StrictHostKeyChecking, no); // 临时测试用session.connect(30000); // 30秒超时System.out.println(连接成功);session.disconnect();} catch (JSchException e) {e.printStackTrace();}}}较新的服务端兼容旧客户端/etc/ssh/sshd_config追加以下内容这里添加的算法取决于Their offer后边提示的类型一般只添加部分即可推荐使用追加额外算法。#解决no matching key exchange method found报错KexAlgorithms diffie-hellman-group14-sha1#解决no matching host key type found报错HostKeyAlgorithms ssh-rsa附查看服务端ssh支持算法hellxzhz:~$ sudo sshd -T | grep -E ^hostkeyalg|^kexalgkexalgorithms sntrup761x25519-sha512openssh.com,curve25519-sha256,curve25519-sha256libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1hostkeyalgorithms ssh-ed25519-cert-v01openssh.com,ecdsa-sha2-nistp256-cert