How to retrieve a file from a server via SFTP?

后端 未结 16 1522
萌比男神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:40

    hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements)

    Example code from SFTPUpload.java

    package net.schmizz.sshj.examples;
    
    import net.schmizz.sshj.SSHClient;
    import net.schmizz.sshj.sftp.SFTPClient;
    import net.schmizz.sshj.xfer.FileSystemFile;
    
    import java.io.File;
    import java.io.IOException;
    
    /** This example demonstrates uploading of a file over SFTP to the SSH server. */
    public class SFTPUpload {
    
        public static void main(String[] args)
                throws IOException {
            final SSHClient ssh = new SSHClient();
            ssh.loadKnownHosts();
            ssh.connect("localhost");
            try {
                ssh.authPublickey(System.getProperty("user.name"));
                final String src = System.getProperty("user.home") + File.separator + "test_file";
                final SFTPClient sftp = ssh.newSFTPClient();
                try {
                    sftp.put(new FileSystemFile(src), "/tmp");
                } finally {
                    sftp.close();
                }
            } finally {
                ssh.disconnect();
            }
        }
    
    }
    

提交回复
热议问题