Retrieving Files via SFTP in Java
When utilizing SFTP rather than FTPS to retrieve files from a remote server, Java developers face a unique challenge. One approach is to explore the JSch library, a widely adopted choice for reputable open-source projects like Eclipse, Ant, and Apache Commons HttpClient.
JSch seamlessly accommodates both username/password and certificate-based logins, offering a comprehensive range of SSH2 capabilities. Below, we present a rudimentary example of retrieving a file over SFTP using JSch:
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();
The above is the detailed content of How Can I Retrieve Files via SFTP in Java Using JSch?. For more information, please follow other related articles on the PHP Chinese website!