How to retrieve a file from a server via SFTP?

后端 未结 16 1631
萌比男神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条回答
  •  天命终不由人
    2020-11-22 08:17

    Though answers above were very helpful, I've spent a day to make them work, facing various exceptions like "broken channel", "rsa key unknown" and "packet corrupt".

    Below is a working reusable class for SFTP FILES UPLOAD/DOWNLOAD using JSch library.

    Upload usage:

    SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png", /path/to/destinationfile.png");
    

    Download usage:

    SFTPFileCopy download = new SFTPFileCopy(false, "/path/to/sourcefile.png", "/path/to/destinationfile.png");
    

    The class code:

    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    import com.jcraft.jsch.UIKeyboardInteractive;
    import com.jcraft.jsch.UserInfo;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import javax.swing.JOptionPane;
    import menue.Menue;
    
    public class SFTPFileCopy1 {
    
        public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {
            Session session = null;
            Channel channel = null;
            ChannelSftp sftpChannel = null;
            try {
                JSch jsch = new JSch();
                //jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
                session = jsch.getSession("login", "mysite.com", 22);
                session.setPassword("password");
    
                UserInfo ui = new MyUserInfo() {
                    public void showMessage(String message) {
    
                        JOptionPane.showMessageDialog(null, message);
    
                    }
    
                    public boolean promptYesNo(String message) {
    
                        Object[] options = {"yes", "no"};
    
                        int foo = JOptionPane.showOptionDialog(null,
                                message,
                                "Warning",
                                JOptionPane.DEFAULT_OPTION,
                                JOptionPane.WARNING_MESSAGE,
                                null, options, options[0]);
    
                        return foo == 0;
    
                    }
                };
                session.setUserInfo(ui);
    
                session.setConfig("StrictHostKeyChecking", "no");
                session.connect();
                channel = session.openChannel("sftp");
                channel.setInputStream(System.in);
                channel.setOutputStream(System.out);
                channel.connect();
                sftpChannel = (ChannelSftp) channel;
    
                if (upload) { // File upload.
                    byte[] bufr = new byte[(int) new File(sourcePath).length()];
                    FileInputStream fis = new FileInputStream(new File(sourcePath));
                    fis.read(bufr);
                    ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);
                    sftpChannel.put(fileStream, destPath);
                    fileStream.close();
                } else { // File download.
                    byte[] buffer = new byte[1024];
                    BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));
                    OutputStream os = new FileOutputStream(new File(destPath));
                    BufferedOutputStream bos = new BufferedOutputStream(os);
                    int readCount;
                    while ((readCount = bis.read(buffer)) > 0) {
                        bos.write(buffer, 0, readCount);
                    }
                    bis.close();
                    bos.close();
                }
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                if (sftpChannel != null) {
                    sftpChannel.exit();
                }
                if (channel != null) {
                    channel.disconnect();
                }
                if (session != null) {
                    session.disconnect();
                }
            }
        }
    
        public static abstract class MyUserInfo
                implements UserInfo, UIKeyboardInteractive {
    
            public String getPassword() {
                return null;
            }
    
            public boolean promptYesNo(String str) {
                return false;
            }
    
            public String getPassphrase() {
                return null;
            }
    
            public boolean promptPassphrase(String message) {
                return false;
            }
    
            public boolean promptPassword(String message) {
                return false;
            }
    
            public void showMessage(String message) {
            }
    
            public String[] promptKeyboardInteractive(String destination,
                    String name,
                    String instruction,
                    String[] prompt,
                    boolean[] echo) {
    
                return null;
            }
        }
    }
    

提交回复
热议问题