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

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

问题描述

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

解决方案

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

它支持用户/通行证和证书基于浏览器的登录,以及所有其他美味的SSH2功能。



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

  JSch jsch = new JSch(); 

字符串knownHostsFilename =/home/username/.ssh/known_hosts;
jsch.setKnownHosts(knownHostsFilename);

会话会话= jsch.getSession(remote-username,remote-host);
{
//交互式版本
//可以选择性地更新指定的known_hosts文件
//需要实现UserInfo接口
// MyUserInfo是一个提供的swing实现在
中// examples / Sftp.java在JSch dist
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);

//或非交互式版本。依赖于主机密钥位于已知主机文件
session.setPassword(remote-password);
}

session.connect();

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

ChannelSftp sftpChannel =(ChannelSftp)频道;

sftpChannel.get(remote-file,local-file);
// OR
InputStream in = sftpChannel.get(remote-file);
//根据需要处理输入流

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


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

解决方案

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.

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

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天全站免登陆