如何通过 SFTP 从服务器检索文件? [英] How to retrieve a file from a server via SFTP?

查看:46
本文介绍了如何通过 SFTP 从服务器检索文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java 使用 SFTP(而不是 FTPS)从服务器检索文件.我该怎么做?

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

推荐答案

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

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.

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

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

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

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

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

这篇关于如何通过 SFTP 从服务器检索文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆