How to retrieve a file from a server via SFTP?

后端 未结 16 1607
萌比男神i
萌比男神i 2020-11-22 07:48

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

16条回答
  •  猫巷女王i
    2020-11-22 08:33

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

提交回复
热议问题