如何通过SFTP从服务器检索文件?

时间:2020-03-05 18:40:23  来源:igfitidea点击:

我正在尝试使用Java使用SFTP(而不是FTPS)从服务器检索文件。我怎样才能做到这一点?

解决方案

回答

这是我想出的解决方案
http://sourceforge.net/projects/sshtools/(为清楚起见,省略了大多数错误处理)。这是我博客的摘录

SshClient ssh = new SshClient();
ssh.connect(host, port);
//Authenticate
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(userName);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if(result != AuthenticationProtocolState.COMPLETE){
     throw new SFTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed");
}
//Open the SFTP channel
SftpClient client = ssh.openSftpClient();
//Send the file
client.put(filePath);
//disconnect
client.quit();
ssh.disconnect();

回答

另一个选择是考虑查看JSch库。 JSch似乎是一些大型开源项目的首选库,其中包括Eclipse,Ant和Apache Commons HttpClient。

它很好地支持用户/通过和基于证书的登录,以及所有其他许多美味的SSH2功能。

这是通过SFTP检索的简单远程文件。错误处理留给读者练习:-)

JSch jsch = new JSch();

String knownHostsFilename = "/home/username/.ssh/known_hosts";
jsch.setKnownHosts( knownHostsFilename );

Session session = jsch.getSession( "remote-username", "remote-host" );    
{
  // "interactive" version
  // can selectively update specified known_hosts file 
  // need to implement UserInfo interface
  // MyUserInfo is a swing implementation provided in 
  //  examples/Sftp.java in the JSch dist
  UserInfo ui = new MyUserInfo();
  session.setUserInfo(ui);

  // OR non-interactive version. Relies in host key being in known-hosts file
  session.setPassword( "remote-password" );
}

session.connect();

Channel channel = session.openChannel( "sftp" );
channel.connect();

ChannelSftp sftpChannel = (ChannelSftp) channel;

sftpChannel.get("remote-file", "local-file" );
// OR
InputStream in = sftpChannel.get( "remote-file" );
  // process inputstream as needed

sftpChannel.exit();
session.disconnect();

回答

Apache commons-vfs是Jsch之上的一个很好的抽象,它提供了一个虚拟文件系统API,该API使访问和写入SFTP文件几乎透明。对我们来说很好。

回答

我找到的最好的解决方案是Paramiko。有一个Java版本。

回答

我们也可以使用带有SFTP添加组件的JFileUpload(也是Java):
http://www.jfileupload.com/products/sftp/index.html

回答

尝试edtFTPj / PRO,这是一个成熟,强大的SFTP客户端库,支持连接池和异步操作。还支持FTP和FTPS,因此涵盖了安全文件传输的所有基础。

回答

我使用了称为Zehon的SFTP API,它很棒,因此很容易与大量示例代码一起使用。这是网站http://www.zehon.com

回答

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

}

回答

以下是使用Apache Common VFS的示例:

FileSystemOptions fsOptions = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
FileSystemManager fsManager = VFS.getManager();
String uri = "sftp://user:password@host:port/absolute-path";
FileObject fo = fsManager.resolveFile(uri, fsOptions);

回答

这是使用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();
        }
    }
}