After searching through the internet i found that most of the people recommend to use JSch from JCraft.
It does not have a comprehensive documentation but it does provide useful example to use the library http://www.jcraft.com/jsch/examples/
Today i am working on a small project to establish SFTP connection by using private key authentication.
public class SftpDemo {
private static final String HOST = "127.0.0.1";
private static final int PORT = 22;
private static final String USER = "root";
private static final String PRIVATE_KEY_LOCATION = "C:\NewFolder\privatekey";
public static void main(String[] args) {
/*
* JSch manages identities and the creation of sessions.
*/
JSch jSch = new JSch();
try {
final byte[] privateKey = getPrivateKeyAsByteStream();
jSch.addIdentity(USER, // String userName
privateKey, // byte[] privateKey
null, // byte[] publicKey
new byte[0] // byte[] passPhrase
);
Session session = jSch.getSession(USER, HOST, PORT);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
ChannelSftp sftp = (ChannelSftp) channel;
sftp.connect();
//list all the files from the sftp directory
final Vector files = sftp.ls(".");
Iterator itFiles = files.iterator();
while (itFiles.hasNext()) {
System.out.println("Index: " + itFiles.next());
}
final ByteArrayInputStream in = new ByteArrayInputStream(
"This is a sample text".getBytes());
//upload file
sftp.put(in, "test.txt", ChannelSftp.OVERWRITE);
sftp.disconnect();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
private static byte[] getPrivateKeyAsByteStream() throws IOException {
final File privKeyLocation = new File(PRIVATE_KEY_LOCATION);
InputStream is = new FileInputStream(privKeyLocation);
long length = privKeyLocation.length();
if (length > Integer.MAX_VALUE) {
throw new IOException(
"File to process is too big to process in this example.");
}
final byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while ((offset < bytes.length)
&& ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "
+ privKeyLocation.getName());
}
is.close();
return bytes;
}
}
Done.