SCP with Java

Secure Copy with Java using JSch

Chanaka Lakmal
Feb 15, 2017 · 2 min read
Source: http://cdn.journaldev.com/wp-content/uploads/2011/02/jsch-example.jpg

SCP (Secure Copy) allows the files in the local file system or a remote file system to be copied to the local files system or a remote file system. This uses SSH for data transfer and provides the same authentication and same level of security as SSH.

Authentication

Authentication between two hosts can be done using the ‘private and public key pair’ or ‘username and password’. But user has to make sure that the public key of the local machine should be saved in authorized_keys of the remote machine.

Test SCP

Note: The remote host can be the same localhost. No need to have a remote machine.

How SCP with Java?

JSch library which is a pure Java implementation of SSH2. JSch allows the user to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and the user can integrate its functionality into the user’s own Java programs. JSch is licensed under BSD style license.

Design and Implementation

Initially, the user has to identify the remote hosts that the user is going to copy the files from and copy the files to. It can be a host name or an IP. Then the user has to create a com.jcraft.jsch.Session using createSession(…) method and parsing the required set of parameters, in order to work with SCP.

In this example the private key is provided for the authentication. So that the public key of local machine is saved in authorized_keys of the remote machine.

This is how the user can SCP files from the remote host to localhost. User has to provide the session he has created using createSession(…) method.

This is how the user can SCP files from localhost to a remote host. User has to provide the session he has created using createSession(…) method.

GitHub Repository: https://github.com/ldclakmal/SCPTransport

References:

Chanaka Lakmal

Written by

Tech Enthusiast | Software Engineer @ WSO2 | Computer Science Engineering @ UoM | Rotaractor | Maliyadeva College

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade