Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsch session.connect() problems

Tags:

java

sftp

jsch

I'm new to Jsch and I'm trying to connect to a third party through sftp. I can connect over ssh so I know I have the right user, host, port and private key file, but when I try to connect through Jsch I get the exception message "Auth failed", which is almost, but not quite, helpful. Here is my code that I pieced together from examples online:

String pvtkey = "{unixpath}/id_dsa";
ChannelSftp sftp = null;
JSch jsch = new JSch();
Session session = null;

try {
    jsch.setKnownHosts("{unixpath}/known_hosts");
    jsch.addIdentity(pvtkey);
    session = jsch.getSession(user, connectionURL, 22);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    // ...some other code that never gets called
} catch (JSchException e) {
    log.info(e.getMessage());
    log.error(e.getCause());
}

I added some logs so I know the failure is happening as session.connect(). I've caught the user and the connectionURL and verified that they are being passed in properly. The path to the pvtkey and known_hosts is the full unix path to where I hold the key and hosts files, which I've moved to a directory that holds the script tht kicks off this process. I'm still a bit new to sftp, does my public key have to be in that same directory even if I'm not adding it to the Jsch connection? Is there some way to get more information on my failure?

like image 767
coffeeNjava Avatar asked Mar 28 '26 00:03

coffeeNjava


1 Answers

Yes, if you are using public-key authentication, JSch is expecting the public-key file in the same directory (and same name with an added .pub) as the private key file you passed as a parameter to addIdentity(). Alternatively, you can use the method variant which takes both file names as parameters, or pass them as byte arrays.

The reason is that in the SSH public key authentication protocol, the client first sends a list of the available public keys to the server, and the server from these selects a fitting one - only then the private key is needed (and will be decrypted, if necessary). While it (depending of the algorithm and key representation) might be possible to calculate the public key from the private one, JSch doesn't do this itself, so you'll have to provide both keys.

like image 62
Paŭlo Ebermann Avatar answered Mar 31 '26 09:03

Paŭlo Ebermann