Friday, June 1, 2012

Using JSch to Copy Files Between Servers

JSch, a pure Java implementation for SSH, SCP and SFTP, is a useful but not very well documented API, and the documented example for SCP is much too complicated (i.e. having to push the files byte by byte via IO streams).

The simplest way to copy a file is via the following:

JSch jsch = new JSch();
jsch.addIdentity("/home/username/.ssh/id_dsa"); // for private key authentication
Session session = jsch.getSession("myusername", "thehost", thePortNumber);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no"); // avoid host key not known warning
session.setConfig(config);
session.connect();
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
for (File file : files) {
    channel.put(file.getAbsolutePath(), "<the dest path>",ChannelSftp.OVERWRITE);
}
channel.disconnect();
session.disconnect();

References:

No comments:

Post a Comment