How to retrieve a file from a server via SFTP?

后端 未结 16 1339
萌比男神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:16

    Andy, to delete file on remote system you need to use (channelExec) of JSch and pass unix/linux commands to delete it.

    0 讨论(0)
  • 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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:18

    Another option is to consider looking at the JSch library. JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.

    It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.

    Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)

    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();
    
    0 讨论(0)
  • 2020-11-22 08:20

    I found complete working example for SFTP in java using JSCH API http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/

    0 讨论(0)
  • 2020-11-22 08:21

    You also have JFileUpload with SFTP add-on (Java too): http://www.jfileupload.com/products/sftp/index.html

    0 讨论(0)
  • 2020-11-22 08:22

    Below is an example using Apache Common VFS:

    FileSystemOptions fsOptions = new FileSystemOptions();
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
    FileSystemManager fsManager = VFS.getManager();
    String uri = "sftp://user:password@host:port/absolute-path";
    FileObject fo = fsManager.resolveFile(uri, fsOptions);
    
    0 讨论(0)
提交回复
热议问题