Back
I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?
Here is the complete source code of an example using JSch without having to worry about the ssh key checking.
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(); } }}
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) {
}
31k questions
32.8k answers
501 comments
693 users