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


当前回答

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

其他回答

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

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

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

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

另一种选择是考虑查看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();