SFTP Processbuilder

1.1k views Asked by At

I have to invoke unix commands from Java and I have to use ProcessBuilder. I want to login through SFTP using key authentication and I want to SFTP the file from local directory to remote location.

ProcessBuilder pb = new ProcessBuilder("sftp","-oIdentityFile=privateKey","-b","commands.txt","username@hostname");

Content in commands.txt is

put localFileDirectory remoteDirectory
exit

Is there any way that I can give localFileDirectory and remoteDirectory in processbuilder? Those should be dynamic and I have to give it processbuilder.

1

There are 1 answers

4
nobody On BEST ANSWER

Two possible approaches:

  1. Use the scp command instead. It does the same ssh-based file transfer, but allows you to specify source and destination on the command line.

    ProcessBuilder pb = new ProcessBuilder("scp", "-i privateKey", "-r",
        "localFileDirectory", "username@hostname:remoteDirectory");
    

    The -r is for "recursive", needed if you are transferring a whole folder. It's not needed if you're just transferring a single file.

  2. Generate the commands.txt file from your Java code.