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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:10:59  来源:igfitidea点击:

How to retrieve a file from a server via SFTP?

javaftpsftpsecurity

提问by David Hayes

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

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

采纳答案by Cheekysoft

Another option is to consider looking at the JSch library. JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.

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

It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.

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

Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)

这是通过 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();

回答by David Hayes

This was the solution I came up with http://sourceforge.net/projects/sshtools/(most error handling omitted for clarity). This is an excerpt from my blog

这是我想出的解决方案 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();

回答by Boris Terzic

A nice abstraction on top of Jsch is Apache commons-vfswhich offers a virtual filesystem API that makes accessing and writing SFTP files almost transparent. Worked well for us.

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

回答by Brian Clapper

The best solution I've found is Paramiko. There's a Java version.

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

回答by Brian Clapper

You also have JFileUpload with SFTP add-on (Java too): http://www.jfileupload.com/products/sftp/index.html

您还有带有 SFTP 附加组件的 JFileUpload(也是 Java):http://www.jfileupload.com/products/sftp/index.html

回答by Bruce Blackshaw

Try edtFTPj/PRO, a mature, robust SFTP client library that supports connection pools and asynchronous operations. Also supports FTP and FTPS so all bases for secure file transfer are covered.

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

回答by Bruce Blackshaw

I use this SFTP API called Zehon, it's great, so easy to use with a lot of sample code. Here is the site http://www.zehon.com

我使用了这个名为 Zehon 的 SFTP API,它很棒,非常容易使用,有很多示例代码。这是网站http://www.zehon.com

回答by shikhar

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

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

Example code from SFTPUpload.java

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

}

回答by Chris J

Below is an example using Apache Common VFS:

下面是一个使用 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);

回答by Iraklis

Here is the complete source code of an example using JSchwithout having to worry about the ssh key checking.

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