Java code to copy files from one linux machine to another linux machine

file-copyjavascp

I'm looking for java code to copy files to a remote linux system. I have tried Runtime.getRuntime().exec() function by passing an scp command, but each time I run the program it is asking for the remote system password. I'd like to avoid that.

I looked at the Jsch library — using this I can login to a remote system — but I can't copy the files to the remote system. Once I login I can do scp to my host but again it requires the host system username and password. However, I only have the remote system's information.

Best Answer

Copying a file from one host to another requires a daemon on the remote host, implementing some application-level file transmission protocol. This is a requirement no matter from which language you are going to talk to that remote daemon.

Your options for Linux systems are:

  • SSH. This requires a SSH daemon (say openssh-server) on the remote side. Because ssh is designed for security you will have to configure the remote host to authenticate you with either a password or a private key. Actually copying the file can be done via the scp utility or ssh client library (jsch would be an example of such).
  • NFS. The remote host installs a daemon (for example samba) and shares some files. Your local computer (cifs-utils package is capable of that) can then mount a remote location on the local file system. This way you can copy a file to the remote host by just copying the file locally. Authentication is optional, files are sent in plain over the network.
  • FTP. An ftp server is installed on remote side and configured to permit access to certain locations for certain users. You can then use any ftp client or some ftp client library (commons-net library from the Apache project, for instance) to connect to the remote ftp server and copy the files. Authentication is optional, files are sent in plain over the network.

All of this seems like a lot of work, and in deed it is, because there is not a single widely-adopted and standardized protocol that would be implemented and configured out-of-the-box on most systems.

Related Question