Search code examples
javasftpjsch

Send files from one remote server using JSch to another server using JSch too


I would like to send files from my first remote server to another one:

public boolean uploadFile() throws JSchException, SftpException {
    ChannelSftp channelSftpA = createChannelSftp();
    ChannelSftp channelSftpB = createChannelSftp();
    channelSftpA.connect();
    channelSftpB.connect();

    localFilePath = "/data/upload/readme.txt";
    remoteFilePath = "/bingo/pdf/";

    channelSftpA.cd(localFilePath);
    channelSftpA.put(localFilePath + "readme.txt", remoteFilePath + "readme.txt");

But it doesn't work. Should I put channelB.put into my first channelA.put?


Solution

  • If I understood your question correct, you code will be run from third server, for transferring file you should get file from server A, and that put on server B. By the way users under which you are going to download and upload files should have access to specified folders!

    private boolean transferFile() throws JSchException, SftpException {
        ChannelSftp channelSftpA = createChannelSftp();
        ChannelSftp channelSftpB = createChannelSftp();
        channelSftpA.connect();
        channelSftpB.connect();
    
        String fileName = "readme.txt";
        String remoteFilePathFrom = "/folderFrom/";
        String remoteFilePathTo = "/folderTo/";
    
        InputStream srcInputStream = channelSftpA.get(remoteFilePathFrom + fileName);
        channelSftpB.put(srcInputStream, remoteFilePathTo + fileName);
        System.out.println("Transfer has been completed");
    
        channelSftpA.exit();
        channelSftpB.exit();
        return true;
    }