How to retrieve a file from a server via SFTP?

后端 未结 16 1358
萌比男神i
萌比男神i 2020-11-22 07:48

I\'m trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?

16条回答
  •  忘了有多久
    2020-11-22 08:23

    There is a nice comparison of the 3 mature Java libraries for SFTP: Commons VFS, SSHJ and JSch

    To sum up SSHJ has the clearest API and it's the best out of them if you don't need other storages support provided by Commons VFS.

    Here is edited SSHJ example from github:

    final SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())
    ssh.connect("localhost");
    try {
        ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name"))
        final SFTPClient sftp = ssh.newSFTPClient();
        try {
            sftp.get("test_file", "/tmp/test.tmp");
        } finally {
            sftp.close();
        }
    } finally {
        ssh.disconnect();
    }
    

提交回复
热议问题