如何使用java中的jschlib通过键盘交互身份验证自动连接到ssh服务器



我想使用jsch通过键盘交互身份验证(或质询-响应身份验证(自动连接到ssh服务器。我已经这样设置了userinfo和config。

session.setUserInfo(myUserInfo);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");

myUserInfo对象实现UserInfo接口当我调试源代码时,我总是得到一个com.jcraf.JSchException:Auth失败异常。有人说myUserInfo应该实现UIKeyboardInteractive。但是我不能理解官方的JSchUserAuthKI示例。太复杂了,无法理解。我只想让连接自动化。谁能给我举个简单的例子。谢谢

我找到了解决方案。让我们的myUserInfo类实现UIKeyboardInteractive接口。并像这样重写了promptKeyboardInteractive方法。

@Override
public String[] promptKeyboardInteractive(String destination, String name,
String instruction, String[] prompt,
boolean[] echo)
{
System.out.println("#####promptKeyboardInteractive#####");
System.out.println("destination: " + destination);
System.out.println("name: " + name);
System.out.println("instruction: " + instruction);
System.out.println("prompt.length: " + prompt.length);
System.out.println("prompt[0]: " + prompt[0]);
System.out.println("echo[0]: " + echo[0]);
String[] response=new String[prompt.length];
response[0] = passwd;
return response;
}

它是有效的。我可以从ssh服务器获得连接。

最新更新