我正在尝试使用Java从使用SFTP(而不是FTPS)的服务器检索文件。我怎样才能做到这一点?
另一个选择是考虑查看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();