I'd like to use JSch to open an SFTP connection to download some files.
String SFTPPRIVATEKEY = "/folder/privatekeyfile";
String SFTPUSER = "user";
String SFTPPASS = "";
String SFTPHOST = "server.tld";
String SFTPPORT = "22";
int usePrivateKey = 1;
public boolean connect() {
boolean isConnected = false;
try {
JSch jsch = new JSch();
if (usePrivateKey) {
jsch.addIdentity(SFTPPRIVATEKEY);
}
session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
if (!usePrivateKey) {
session.setPassword(SFTPPASS);
}
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
if (session.isConnected() == true) {
log.println("Connection to Session server is successfully");
}
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
isConnected = true;
} catch (JSchException e) {
log.println("SFTPClient Connect ERROR: "+e.getMessage());
e.printStackTrace();
}
return isConnected;
}
If i run my code i get:
com.jcraft.jsch.JSchException: USERAUTH fail
I tried to connect using sftp
on the shell on the same client where my Java code runs. I run
sftp -i privatekeyfile [email protected]
It prompts for a passphrase for the privatekeyfile. I entered the passphrase and the connection works great.
But JSch did not connect. I found no option to set the passphrase in JSch. Maybe this is the problem?
Can some of you help?
Thanks
There's JSch.addIdentity
overload that takes the passphrase:
public void addIdentity(String prvkey, String passphrase)
Obligatory warning: Do not use StrictHostKeyChecking=no
to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks. For the correct (and secure) approach, see: How to resolve Java UnknownHostKey, while using JSch SFTP library?