Friday 4 June 2021

How to establish a connection to Remote Host & Copy file

Many times we do get the requirement, to connect a remote server & perform operations like copying a file from local to remote, vice versa and many others. But, have you ever thought how do we do that through java.? Yes, We can. Java has multiple libraries which can perform this task. One such java library which can perform this task is Jcraft's 'JSch (Java Secure Channel)' . 

Below example will let you know how to connect a remote host & perform copy operations.


public void copyFiletoRemotehost(String username,String pwd,String[] remotehosts, String port) {
        Session jschSession = null;
        int SESSION_TIMEOUT = 10000;
        final int CHANNEL_TIMEOUT = 5000;
        String REMOTE_HOST = "";
        int REMOTE_PORT = 22;
		
	String lFile = "C:/localhost/local.txt";
        String rFile = "/localtoRemote.txt";
        try {
            JSch jsch = new JSch();
            for(int i=0; i < remotehosts.length; i++) {
            	REMOTE_HOST = remotehosts[i].toString();
            	jschSession = jsch.getSession(username, REMOTE_HOST, REMOTE_PORT);

                //Remove known_hosts requirement
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                jschSession.setConfig(config);
                
                //authenticate using password
                jschSession.setPassword(pwd);
                jschSession.connect(SESSION_TIMEOUT);
                Channel sftp = jschSession.openChannel("sftp");
                sftp.connect(CHANNEL_TIMEOUT);

                ChannelSftp channelSftp = (ChannelSftp) sftp;
                channelSftp.put(lFile, rFile);
                channelSftp.exit();
                
                //Copy from one location to another with remote server
                copyFile(jschSession);
                jschSession.disconnect();
            }
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        } finally {
            if (jschSession != null) {
                jschSession.disconnect();
            }
        }
    }
    
    /**
    * This method will let you copy from one folder to another within the remote server
    */
    public static void copyFile(Session jschSession) throws JSchException {
	String cmd1 = "cp C:/username/localtoRemote.txt  C:/anotherfolder/localtoRemote.txt";
	Channel exec = jschSession.openChannel("exec");
		
	ChannelExec channelExec = (ChannelExec) exec;
	channelExec.setCommand(cmd1);
	exec.connect(CHANNEL_TIMEOUT);
	channelExec.setErrStream(System.err);
   }

References:
http://www.jcraft.com/jsch/