我试图使用Java使用SFTP(而不是FTPS)从服务器检索一个文件。我该怎么做呢?


当前回答

有3个成熟的用于SFTP的Java库:Commons VFS、SSHJ和JSch

总而言之,如果你不需要Commons VFS提供的其他存储支持,那么SSHJ具有最清晰的API,是其中最好的API。

下面是从github编辑的SSHJ示例:

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();
}

其他回答

尝试edtFTPj/PRO,这是一个成熟、健壮的SFTP客户端库,支持连接池和异步操作。还支持FTP和FTPS,因此安全文件传输的所有基础都包括在内。

我发现完整的工作示例SFTP在java使用JSCH API http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/

你也有JFileUpload SFTP插件(Java也是): http://www.jfileupload.com/products/sftp/index.html

下面是使用JSch的示例的完整源代码,无需担心ssh密钥检查。

import com.jcraft.jsch.*;

public class TestJSch {
    public static void main(String args[]) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("username", "127.0.0.1", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("password");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get("remotefile.txt", "localfile.txt");
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();  
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
}

hierynomus/sshj有一个完整的SFTP版本3的实现(OpenSSH实现的)

来自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();
        }
    }

}