Java 连接到 SFTP 导致身份验证失败

问题描述 投票:0回答:1

我在SpringBoot3中使用Java20。我正在尝试连接到 SFTP 服务器,但出现错误。

我可以连接到FileZilla中的服务器,这证明服务器可用。

但是,当我尝试使用以下代码(使用相同的主机名、端口、用户和密码)在 Java 应用程序中进行连接时:

代码

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            logger.info("About to connect to ["+SFTPHOST+":"+SFTPPORT+" workingdir: "+SFTPWORKINGDIR+" user: "+SFTPUSER+"] via SFTP.");
            session.connect();

执行时出错

session.connect();

错误

com.jcraft.jsch.JSchException: Auth fail
  at com.jcraft.jsch.Session.connect(Session.java:519) ~[jsch-0.1.55.jar:na]
  at com.jcraft.jsch.Session.connect(Session.java:183) ~[jsch-0.1.55.jar:na]

更多信息

我给出以下信息:

ssh-rsa ABC....x==

想要证书。

所以我使用以下作为密码:

ABC....x==

我使用它作为 FileZilla 和 Java 应用程序的密码。

如果我尝试:

jsch.addIdentity(SFTPPUBKEY); // location of the ssh-rsa public key

出现此错误:

com.jcraft.jsch.JSchException: invalid privatekey: [B@16ea43f7

所以

jsch.addIdentity
需要私钥,但我只有公钥。

如果我将其设置为使用我的客户私钥:

jsch.addIdentity("~/.ssh/id_rsa");

出现以下错误:

com.jcraft.jsch.JSchException: invalid privatekey: [B@42991519
java authentication sftp jsch
1个回答
0
投票

感谢上面评论中的 Matthias Wiedemann。我升级到了那个版本的

jsch
现在它可以工作了,我可以连接。问题是它不接受我的 OPENSSH 密钥格式的私钥,而这个新版本则接受。

这意味着我将我的 Maven 依赖项更改为:

    <dependency>
        <groupId>com.github.mwiede</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.61</version>
    </dependency>

来自:

    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.55</version>
    </dependency>

我也:

        jsch.addIdentity(SFTPRIVKEY);  // private key on client (`~/.ssh/id_rsa`)
© www.soinside.com 2019 - 2024. All rights reserved.