Scp through java

What is the best way to do scp transfer through Java programming language? I seem to be able to accomplish this via JSSE, JSch, or the bouncy jown java libraries. None of these solutions have a simple answer.

+71
java scp bouncycastle jsse jsch
Oct. 14 '08 at 0:50
source share
14 answers

I ended up using Jsch - it was pretty simple and seemed to scale pretty well (I grabbed several thousand files every few minutes).

+52
Oct. 14 '08 at 1:22
source share

plug: sshj is the only smart choice! To get started, consider these examples: download , upload .

+18
Mar 08 '10 at 21:15
source share

Look here

This is the source code for the SCP Ants task. The code in the execute method is nuts and bolts. This should give you an idea of ​​what is required. He uses JSch, I believe.

Alternatively, you can also perform this Ant task from your java code.

+16
Oct 14 '08 at 0:57
source share

I wrapped Jsch with some utility methods to make it a little friendlier and called it

Jscp

Available here: https://github.com/willwarren/jscp

SCP utility for archiving a folder, archiving it and copying it to another location, and then unzipping it.

Using:

// 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") ); 

It also includes useful classes - Scp and Exec and TarAndGzip, which work almost the same way.

+6
Dec 25 '12 at 22:25
source share

This is a high-level solution , no need to invent. Quick and dirty!

1) First go to http://ant.apache.org/bindownload.cgi and download the latest Apache Ant binary. (currently apache-ant-1.9.4-bin.zip).

2) Extract the downloaded file and find the JAR file ant-jsch.jar ("apache-ant-1.9.4 / lib / ant-jsch.jar"). Add this JAR to your project . Also ant-launcher.jar and ant.jar.

3) Go into the Jcraft jsch SouceForge project and load the jar. Currently jsch-0.1.52.jar . Also add this JAR to your project .

Now you can easily use Ant Classes Scp in Java code to copy files over the network or SSHExec for commands on SSH servers.

4) Example Scp code:

 // This make scp copy of // one local file to remote dir org.apache.tools.ant.taskdefs.optional.ssh.Scp scp = new Scp(); int portSSH = 22; String srvrSSH = "ssh.your.domain"; String userSSH = "anyuser"; String pswdSSH = new String ( jPasswordField1.getPassword() ); String localFile = "C:\\localfile.txt"; String remoteDir = "/uploads/"; scp.setPort( portSSH ); scp.setLocalFile( localFile ); scp.setTodir( userSSH + ":" + pswdSSH + "@" + srvrSSH + ":" + remoteDir ); scp.setProject( new Project() ); scp.setTrust( true ); scp.execute(); 
+4
Apr 05 '15 at 14:39
source share

openssh project contains several Java alternatives, Trilead SSH for Java seems to match what you ask.

+2
Oct. 14 '08 at 0:56
source share

I use this SFTP-API, which has an SCP called Zehon, it is great, so easy to use with lots of code samples. Here is the website http://www.zehon.com

+2
Jun 18 '09 at 8:26
source share

I looked at many of these solutions and many did not like. Mostly because of the annoying step to identify your famous hosts. This and AOX are ridiculously low relative to the scp team.

I found a library that does not require this, but it is bundled and used as a command line tool. https://code.google.com/p/scp-java-client/

I looked at the source code and found how to use it without a command line. Here is an example download:

  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 drawback is that it is not in the maven repository (which I could find). But ease of use is worth it to me.

+2
Oct 24 '13 at 16:58
source share

Like here, I ended up writing a wrapper around the JSch library.

He called way-secshell and 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(); 
+1
Jan 08 '14 at 15:46
source share

I wrote a scp server that is much simpler than others. I am using the Apache MINA project (Apache SSHD) to develop it. You can look here: https://github.com/boomz/JSCP You can also download the jar file from the /jar directory. How to use? Take a look: https://github.com/boomz/JSCP/blob/master/src/Main.java

0
Jul 14 '13 at 19:28
source share

JSch is a good library to work with. You have a fairly simple answer to your question.

 JSch jsch=new JSch(); Session session=jsch.getSession(user, host, 22); session.setPassword("password"); Properties config = new Properties(); config.put("StrictHostKeyChecking","no"); session.setConfig(config); session.connect(); boolean ptimestamp = true; // exec 'scp -t rfile' remotely String command="scp " + (ptimestamp ? "-p" :"") +" -t "+rfile; Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand(command); // get I/O streams for remote scp OutputStream out=channel.getOutputStream(); InputStream in=channel.getInputStream(); channel.connect(); if(checkAck(in)!=0){ System.exit(0); } File _lfile = new File(lfile); if(ptimestamp){ command="T "+(_lfile.lastModified()/1000)+" 0"; // The access time should be sent here, // but it is not accessible with JavaAPI ;-< command+=(" "+(_lfile.lastModified()/1000)+" 0\n"); out.write(command.getBytes()); out.flush(); if(checkAck(in)!=0){ System.exit(0); } } 

You can find the full code in

http://faisalbhagat.blogspot.com/2013/09/java-uploading-file-remotely-via-scp.html

0
Sep 08 '13 at 12:35 on
source share

jsCH did a great job with me. The following is an example of a method that will connect to the sftp server and upload files to the specified directory. It is recommended that you disable StrictHostKeyChecking. Although a little trickier to configure, for security reasons, specifying known hosts should be the norm.

jsch.setKnownHosts ("C: \ Users \ test \ known_hosts"); recommended

JSch.setConfig ("StrictHostKeyChecking", "no"); - Not recommended

 import com.jcraft.jsch.*; public void downloadFtp(String userName, String password, String host, int port, String path) { Session session = null; Channel channel = null; try { JSch ssh = new JSch(); JSch.setConfig("StrictHostKeyChecking", "no"); session = ssh.getSession(userName, host, port); session.setPassword(password); session.connect(); channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; sftp.get(path, "specify path to where you want the files to be output"); } catch (JSchException e) { System.out.println(userName); e.printStackTrace(); } catch (SftpException e) { System.out.println(userName); e.printStackTrace(); } finally { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } } 
0
Oct 24 '13 at 20:44
source share

I need to copy the folder recursively, after trying various solutions, eventually end up using ProcessBuilder + Expect / Spawn

 scpFile("192.168.1.1", "root","password","/tmp/1","/tmp"); public void scpFile(String host, String username, String password, String src, String dest) throws Exception { String[] scpCmd = new String[]{"expect", "-c", String.format("spawn scp -r %s %s@%s:%s\n", src, username, host, dest) + "expect \"?assword:\"\n" + String.format("send \"%s\\r\"\n", password) + "expect eof"}; ProcessBuilder pb = new ProcessBuilder(scpCmd); System.out.println("Run shell command: " + Arrays.toString(scpCmd)); Process process = pb.start(); int errCode = process.waitFor(); System.out.println("Echo command executed, any errors? " + (errCode == 0 ? "No" : "Yes")); System.out.println("Echo Output:\n" + output(process.getInputStream())); if(errCode != 0) throw new Exception(); } 
0
Jan 19 '18 at 3:41
source share

Here is an example to download a file using JSch :

ScpUploader.java :

 import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; import java.io.ByteArrayInputStream; import java.util.Properties; public final class ScpUploader { public static ScpUploader newInstance() { return new ScpUploader(); } private volatile Session session; private volatile ChannelSftp channel; private ScpUploader(){} public synchronized void connect(String host, int port, String username, String password) throws JSchException { JSch jsch = new JSch(); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session = jsch.getSession(username, host, port); session.setPassword(password); session.setConfig(config); session.setInputStream(System.in); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); } public synchronized void uploadFile(String directoryPath, String fileName, byte[] fileBytes, boolean overwrite) throws SftpException { if(session == null || channel == null) { System.err.println("No open session!"); return; } // a workaround to check if the directory exists. Otherwise, create it channel.cd("/"); String[] directories = directoryPath.split("/"); for(String directory : directories) { if(directory.length() > 0) { try { channel.cd(directory); } catch(SftpException e) { // swallowed exception System.out.println("The directory (" + directory + ") seems to be not exist. We will try to create it."); try { channel.mkdir(directory); channel.cd(directory); System.out.println("The directory (" + directory + ") is created successfully!"); } catch(SftpException e1) { System.err.println("The directory (" + directory + ") is failed to be created!"); e1.printStackTrace(); return; } } } } channel.put(new ByteArrayInputStream(fileBytes), directoryPath + "/" + fileName, overwrite ? ChannelSftp.OVERWRITE : ChannelSftp.RESUME); } public synchronized void disconnect() { if(session == null || channel == null) { System.err.println("No open session!"); return; } channel.exit(); channel.disconnect(); session.disconnect(); channel = null; session = null; } } 

AppEntryPoint.java :

 import com.jcraft.jsch.JSchException; import com.jcraft.jsch.SftpException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public final class AppEntryPoint { private static final String HOST = "192.168.1.1"; private static final int PORT = 22; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; public static void main(String[] args) throws IOException { ScpUploader scpUploader = ScpUploader.newInstance(); try { scpUploader.connect(HOST, PORT, USERNAME, PASSWORD); } catch(JSchException e) { System.err.println("Failed to connect the server!"); e.printStackTrace(); return; } System.out.println("Successfully connected to the server!"); byte[] fileBytes = Files.readAllBytes(Paths.get("C:/file.zip")); try { scpUploader.uploadFile("/test/files", "file.zip", fileBytes, true); // if overwrite == false, it won't throw exception if the file exists System.out.println("Successfully uploaded the file!"); } catch(SftpException e) { System.err.println("Failed to upload the file!"); e.printStackTrace(); } scpUploader.disconnect(); } } 
0
Jul 21 '19 at 12:25
source share



All Articles