java端使用密钥认证创建ssh连接,出现读取id_rsa, id_dsa出错的可能原因

原文链接: https://my.oschina.net/u/3706162/blog/2967281

问题重现:
1. 首先在mac的ssh命令行中,使用ssh-keygen生成rsa密钥,并且将公钥复制到目标服务器的/root/.ssh/authorized_keys文件中
2. 使用命令行 ssh root@host 免密登录没有问题
3. 接着使用sshj进行ssh连接

String hostname ="1.1.1.1";
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
		
client.loadKnownHosts();
//logger.debug("connect to "+hostname+" port:"+port);
client.setConnectTimeout(1000);
client.connect(hostname);

client.authPublickey("root");

4. 此时,authpublickey方法报出的root cause错误如下

.........
.........Exhausted available authentication methods
.......
net.schmizz.sshj.common.Buffer.readString Bad item length
......

5. 改用jsch进行ssh连接,代码如下

JSch jsch = new JSch();
jsch.addIdentity("/root/.ssh/id_rsa","");
Session session=jsch.getSession(userName, hostIp, 22);
UserInfo ui=new CustomUserInfo();
session.setUserInfo(ui);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();

6. 出现错误

com.jcraft.jsch.JSchException: invalid privatekey: [B@413620d8

 

解决问题:

尝试了很多网上提供的解决方案都是关于代码层面的修改,无果。其实问题关键出在了使用mac生成的密钥。后来使用了linux的ssh-keygen生成密钥,并将密钥复制到mac的/Users/{user}/.ssh 目录下,并且赋予id_rsa 600权限,id_rsa.pub 700权限后,问题解决。

转载于:https://my.oschina.net/u/3706162/blog/2967281

你可能感兴趣的:(java端使用密钥认证创建ssh连接,出现读取id_rsa, id_dsa出错的可能原因)