【问题标题】:Get files from sftp using sshj and PuttyKeyFile使用 sshj 和 PuttyKeyFile 从 sftp 获取文件
【发布时间】:2021-09-10 09:17:27
【问题描述】:

我正在尝试从 sftp 服务器获取文件,但即使我尝试了许多不同的方法,它仍然给我一个错误 userauth.UserAuthenticationExeption: "Exhausted available authentication methods" 和 IllegalStateException: "Not authenticated"

使用 putty 和 app PSFTP,我可以使用 key.ppk、用户名和密码轻松登录服务器。在 PSFTP 身份验证中工作正常。

我的 key.ppk 看起来像:

PuTTy-User-Key-File-2: ssh-rsa
Encryption: none
Comment: rsa-key-randomInt
Private-Lines: randomInt
Some random key

另外几行,就像我说的,使用 PSFTP 我可以使用这个密钥登录,所以我知道它有效。

我的代码示例:

var client = new SSHClient();
client.setTimeout(config.getTimeout());
client.setConnectTimeout(config.getTimeout());
client.addHostKeyVerifier(new PromiscuousVerifier());

try{
   client.connect(config.getHost, config.getPort());
} catch (IOException e){
   e.printStackTrace();
}

var passwordAuth = ObjectUtils.isEmpty(config.getPassword())
   ? List<AuthMethod>empty()
   : List.of<new AuthPassword(PasswordUtils.createOneOff(config.getPassword.toCharArray()));

List< ? extends AuthMethod> key = null;

try{
   key = ObjectUtils.isEmpty(config.getPrivateKey())
   ? List<AuthMethod>empty()
   : List.of(new AuthPublicKey(createKeyProvider()));
}

createKeyProvider KeyPairWrapper createKeyProvider() throws IOException{
   PuttyKeyFile puttyKeyFile = new PuttyKeyFile();
   putyKeyfile.init(new File(path));//it works, in debug it shows proper object with values

  return new KeyPairWrapper(new KeyPair(puttyKeyFile.getPublic(), puttyKeyFile.getPrivate))
}

var authMethods = List.of(passwordAuth).<AuthMethod>flatMap(Function.identity());

try{
   client.auth(
      config.getUsername(),
      authMethods
   );
}catch(UserAuthException e){
   e.printStackTrace();
}

如果我打错了,很抱歉,但我需要重写代码示例而不是复制粘贴。

在我开始工作之前,此代码的一部分是由其他人(无法帮助我)编写的。我认为我需要使用用户名、密钥和密码登录。我尝试仅使用 client.auth(username, password) 或 client.auth(username, key) 登录,但它不起作用,当我尝试使用 PSFTP 登录时,我需要使用这 3 个东西。

我认为问题出在 AuthPublicKey 中,我尝试添加许多不同的对象,例如:KeyPair、KeyPairWrapper、client.loadKey(fileLocation)、client.loadKey(keyPair)。

我也将此ppk文件转换为其他格式,并尝试获取密钥,但仍然报同样的错误。

我尝试的另一件事是不提供端口,多次检查配置,当我使用 PSFTP 登录服务器时,我复制了值以检查是否有错字。

我开始迷失方向,寻找新的解决方法。在完美的情况下,我想从配置文件中获取我的密钥,我也尝试过这样做,但我仍然在这里。

如果您有如何获得身份验证的解决方案,或者只是知道可能出了什么问题,我将不胜感激。

谢谢你们,我会得到任何帮助。

【问题讨论】:

    标签: java sshj psftp


    【解决方案1】:

    好的,我用黄鸭法解决问题。问题不在 AuthPublicKey 中,问题是,我正确创建了它,但我没有将它添加到列表 authMethods。

    //WRONG
    var authMethods = List.of(passwordAuth).<AuthMethod>flatMap(Function.identity());
    
    //OK
    var authMethods = List.of(passwordAuth, key).<AuthMethod>flatMap(Function.identity());
    

    缺少 key 属性。 现在可以了,很抱歉浪费你的时间,但我真的没听懂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多