Copy file from a local to the remote server using Java

Earlier, we discussed how to connect with a secure server using ssh and then how we can execute the commands on that remote server. This post will discuss how we can copy or transfer the files from a local server to a remote server.

We will use the JSch library to connect and transfer the files from our local system to the remote server.

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
How to copy files from a local to a remote machine?
Connect to a secure server first

We have written a different post on connecting with a server using ssh. Below is the code on how we can connect to a server.

	public void connect(String username, String password, String host, int port, String FILE_KEY_NAME) {
		try {

			JSch jsch = new JSch();

			// if there is a key, then connect using that key
			// otherwise, we will connect using a password
			if (FILE_KEY_NAME != null && !FILE_KEY_NAME.equals("")) {
				jsch.addIdentity(FILE_KEY_NAME);
				session = jsch.getSession(username, host, port);
			} else {
				session = jsch.getSession(username, host, port);
				session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
				session.setPassword(password);
			}

			session.setConfig("StrictHostKeyChecking", "no");
			session.setTimeout(15000);
			session.connect();

			System.out.println("Connected to: " + host);

		} catch (JSchException e) {
			e.printStackTrace();
            session.disconnect();
		}

	}
  • Connecting with a remote server can be two ways: a password or a key.
  • If you have a key, you can pass the “key” file path into the connect() function, and then the key will be used to connect with the remote server.
  • But if you don’t have a key, the password will be used to connect with the server.
Transfer the file from the local to the remote machine

We can transfer the files by opening an SFTP connection and then using the put method to copy or transfer the files from the local machine to the remote server.

	public void copyFilesToAnotherMachine1(String localFilePath, String remoteFilePath) {

		try {
			Channel sftp = session.openChannel("sftp");

			sftp.connect(15000);

			ChannelSftp channelSftp = (ChannelSftp) sftp;

			channelSftp.put(localFilePath, remoteFilePath);

			channelSftp.exit();
			session.disconnect();

		} catch (JSchException | SftpException e) {

			e.printStackTrace();
            session.disconnect();
		}

	}

The whole program to copy or transfer a file from a local machine to a remote machine would be like this –

import com.jcraft.jsch.Channel;
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;

public class Codekru {

	Session session;

	public static void main(String[] args) {
		String remoteHostPort = "127.0. 0.1"; // Your remote host ip
		String username = "codekru"; // Your username
		String password = "codekru"; // Your password
		int port = 22; // The port (Default port is 22 )

		// your local machine path of the file
		String localfilePath = "/usr/codekru/files/file1.txt";

		// your remote machine path for the file
		String remoteFilePath = "/usr/workspace/remoteFile.txt";

		Codekru codekru = new Codekru();

		codekru.connect(username, password, remoteHostPort, port, null);
		codekru.copyAFileToRemoteMachine(localfilePath, remoteFilePath);
	}

	public void connect(String username, String password, String host, int port, String FILE_KEY_NAME) {
		try {

			JSch jsch = new JSch();

			// if there is a key, then connect using that key
			// otherwise, we will connect using a password
			if (FILE_KEY_NAME != null && !FILE_KEY_NAME.equals("")) {
				jsch.addIdentity(FILE_KEY_NAME);
				session = jsch.getSession(username, host, port);
			} else {
				session = jsch.getSession(username, host, port);
				session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
				session.setPassword(password);
			}

			session.setConfig("StrictHostKeyChecking", "no");
			session.setTimeout(15000);
			session.connect();

			System.out.println("Connected to: " + host);

		} catch (JSchException e) {
			e.printStackTrace();
            session.disconnect();
		}

	}

	public void copyAFileToRemoteMachine(String localFilePath, String remoteFilePath) {

		try {
			Channel sftp = session.openChannel("sftp");

			sftp.connect(15000);

			ChannelSftp channelSftp = (ChannelSftp) sftp;

			channelSftp.put(localFilePath, remoteFilePath);

			System.out.println("File has been transferred...");
			
			channelSftp.exit();
			session.disconnect();

		} catch (JSchException | SftpException e) {

			e.printStackTrace();
            session.disconnect();
		}

	}

}

We have used a password to connect with the remote machine, but you might have a key instead of a password to connect with your remote server. In that case, you can pass the key path into the connect() function, and it will use the key to connect with your remote server.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Related Articles –
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *