What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libr
I ended up using Jsch- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).
I use this SFTP API which has SCP called Zehon, it's great, so easy to use with a lot of sample code. Here is the site http://www.zehon.com
I wrapped Jsch with some utility methods to make it a bit friendlier and called it
Available here: https://github.com/willwarren/jscp
SCP utility to tar a folder, zip it, and scp it somewhere, then unzip it.
Usage:
// create secure context
SecureContext context = new SecureContext("userName", "localhost");
// set optional security configurations.
context.setTrustAllHosts(true);
context.setPrivateKeyFile(new File("private/key"));
// Console requires JDK 1.7
// System.out.println("enter password:");
// context.setPassword(System.console().readPassword());
Jscp.exec(context,
"src/dir",
"destination/path",
// regex ignore list
Arrays.asList("logs/log[0-9]*.txt",
"backups")
);
Also includes useful classes - Scp and Exec, and a TarAndGzip, which work in pretty much the same way.
Take a look here
That is the source code for Ants' SCP task. The code in the "execute" method is where the nuts and bolts of it are. This should give you a fair idea of what is required. It uses JSch i believe.
Alternatively you could also directly execute this Ant task from your java code.
I looked at a lot of these solutions and didn't like many of them. Mostly because the annoying step of having to identify your known hosts. That and JSCH is at a ridiculously low level relative to the scp command.
I found a library that doesn't require this but it's bundled up and used as a command line tool. https://code.google.com/p/scp-java-client/
I looked through the source code and discovered how to use it without the command line. Here's an example of uploading:
uk.co.marcoratto.scp.SCP scp = new uk.co.marcoratto.scp.SCP(new uk.co.marcoratto.scp.listeners.SCPListenerPrintStream());
scp.setUsername("root");
scp.setPassword("blah");
scp.setTrust(true);
scp.setFromUri(file.getAbsolutePath());
scp.setToUri("root@host:/path/on/remote");
scp.execute();
The biggest downside is that it's not in a maven repo (that I could find). But, the ease of use is worth it to me.
Like some here, I ended up writing a wrapper around the JSch library.
It's called way-secshell and it is hosted on GitHub:
https://github.com/objectos/way-secshell
// scp myfile.txt localhost:/tmp
File file = new File("myfile.txt");
Scp res = WaySSH.scp()
.file(file)
.toHost("localhost")
.at("/tmp")
.send();