My task is to copy some files from server to local, I have searched a lot about connectivity libraries and found JSch. I have used below code but it is taking too much time to read or move the file. I don't know whether it is working or not.
JSch jsch = new JSch();
Session session = null;
try {
// set up session
session = jsch.getSession("userName","hostIP");
// use private key instead of username/password
session.setConfig(
"PreferredAuthentications",
"publickey,gssapi-with-mic,keyboard-interactive,password");
jsch.addIdentity("***.ppk");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
// copy remote log file to localhost.
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.setInputStream(System.in);
channelSftp.setOutputStream(System.out);
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channelSftp;
System.out.println("done");
channelSftp.get("report.xml", "C:\\Users\\akrishnan");
channelSftp.exit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
}
Is there any library that I can use to connect the servers from my Java code using private key file (**.ppk)?
This is most likely, what causes the hang:
channelSftp.setInputStream(System.in);
channelSftp.setOutputStream(System.out);
Doing that for an "sftp" channel breaks everything. It makes no sense. Just remove those two lines.
Check the official JSch SFTP example – There are no such calls.
For a correct code for file transfers using JSch, see: SFTP file transfer using Java JSch.
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 a correct (and secure) approach, see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?