简体   繁体   English

如何通过 SFTP 从服务器检索文件?

[英]How to retrieve a file from a server via SFTP?

I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java.我正在尝试使用 Java 使用 SFTP(而不是 FTPS)从服务器检索文件。 How can I do this?我怎样才能做到这一点?

Another option is to consider looking at the JSch library .另一种选择是考虑查看JSch 库 JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others. JSch 似乎是一些大型开源项目的首选库,包括 Eclipse、Ant 和 Apache Commons HttpClient 等。

It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.它很好地支持用户/密码和基于证书的登录,以及所有其他美味的 SSH2 功能。

Here's a simple remote file retrieve over SFTP.这是一个通过 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();

Here is the complete source code of an example using JSch without having to worry about the ssh key checking.这是使用JSch的示例的完整源代码,无需担心 ssh 密钥检查。

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

Below is an example using Apache Common VFS:下面是一个使用 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);

A nice abstraction on top of Jsch is Apache commons-vfs which offers a virtual filesystem API that makes accessing and writing SFTP files almost transparent. Jsch 之上的一个很好的抽象是 Apache commons-vfs ,它提供了一个虚拟文件系统 API,使得访问和写入 SFTP 文件几乎是透明的。 Worked well for us.为我们工作得很好。

This was the solution I came up with http://sourceforge.net/projects/sshtools/ (most error handling omitted for clarity).这是我提出的解决方案http://sourceforge.net/projects/sshtools/ (为清楚起见省略了大多数错误处理)。 This is an excerpt from my blog这是我博客的摘录

SshClient ssh = new SshClient();
ssh.connect(host, port);
//Authenticate
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(userName);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if(result != AuthenticationProtocolState.COMPLETE){
     throw new SFTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed");
}
//Open the SFTP channel
SftpClient client = ssh.openSftpClient();
//Send the file
client.put(filePath);
//disconnect
client.quit();
ssh.disconnect();

There is a nice comparison of the 3 mature Java libraries for SFTP: Commons VFS, SSHJ and JSch对 SFTP 的 3 个成熟 Java 库进行了很好的比较: Commons VFS、SSHJ 和 JSch

To sum up SSHJ has the clearest API and it's the best out of them if you don't need other storages support provided by Commons VFS.综上所述,SSHJ 拥有最清晰的 API,如果您不需要 Commons VFS 提供的其他存储支持,它是其中最好的。

Here is edited SSHJ example from github :这是来自github的编辑 SSHJ 示例:

final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())
ssh.connect("localhost");
try {
    ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name"))
    final SFTPClient sftp = ssh.newSFTPClient();
    try {
        sftp.get("test_file", "/tmp/test.tmp");
    } finally {
        sftp.close();
    }
} finally {
    ssh.disconnect();
}

See http://www.mysamplecode.com/2013/06/sftp-apache-commons-file-download.html请参阅http://www.mysamplecode.com/2013/06/sftp-apache-commons-file-download.html

Apache Commons SFTP library Apache Commons SFTP 库

Common java properties file for all the examples所有示例的通用 java 属性文件

serverAddress=111.222.333.444服务器地址=111.222.333.444

userId=myUserId用户 ID=我的用户 ID

password=myPassword密码=我的密码

remoteDirectory=products/远程目录=产品/

localDirectory=import/本地目录=进口/

Upload file to remote server using SFTP使用 SFTP 将文件上传到远程服务器

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
 
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
 
public class SendMyFiles {
 
 static Properties props;
 
 public static void main(String[] args) {
 
  SendMyFiles sendMyFiles = new SendMyFiles();
  if (args.length < 1)
  {
   System.err.println("Usage: java " + sendMyFiles.getClass().getName()+
     " Properties_file File_To_FTP ");
   System.exit(1);
  }
 
  String propertiesFile = args[0].trim();
  String fileToFTP = args[1].trim();
  sendMyFiles.startFTP(propertiesFile, fileToFTP);
 
 }
 
 public boolean startFTP(String propertiesFilename, String fileToFTP){
 
  props = new Properties();
  StandardFileSystemManager manager = new StandardFileSystemManager();
 
  try {
 
   props.load(new FileInputStream("properties/" + propertiesFilename));
   String serverAddress = props.getProperty("serverAddress").trim();
   String userId = props.getProperty("userId").trim();
   String password = props.getProperty("password").trim();
   String remoteDirectory = props.getProperty("remoteDirectory").trim();
   String localDirectory = props.getProperty("localDirectory").trim();
 
   //check if the file exists
   String filepath = localDirectory +  fileToFTP;
   File file = new File(filepath);
   if (!file.exists())
    throw new RuntimeException("Error. Local file not found");
 
   //Initializes the file manager
   manager.init();
    
   //Setup our SFTP configuration
   FileSystemOptions opts = new FileSystemOptions();
   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
     opts, "no");
   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
    
   //Create the SFTP URI using the host name, userid, password,  remote path and file name
   String sftpUri = "sftp://" + userId + ":" + password +  "@" + serverAddress + "/" + 
     remoteDirectory + fileToFTP;
    
   // Create local file object
   FileObject localFile = manager.resolveFile(file.getAbsolutePath());
 
   // Create remote file object
   FileObject remoteFile = manager.resolveFile(sftpUri, opts);
 
   // Copy local file to sftp server
   remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
   System.out.println("File upload successful");
 
  }
  catch (Exception ex) {
   ex.printStackTrace();
   return false;
  }
  finally {
   manager.close();
  }
 
  return true;
 }
 
  
}

Download file from remote server using SFTP使用 SFTP 从远程服务器下载文件

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
 
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
 
public class GetMyFiles {
 
 static Properties props;
 
 public static void main(String[] args) {
 
  GetMyFiles getMyFiles = new GetMyFiles();
  if (args.length < 1)
  {
   System.err.println("Usage: java " + getMyFiles.getClass().getName()+
   " Properties_filename File_To_Download ");
   System.exit(1);
  }
 
  String propertiesFilename = args[0].trim();
  String fileToDownload = args[1].trim();
  getMyFiles.startFTP(propertiesFilename, fileToDownload);
    
 }
 
 public boolean startFTP(String propertiesFilename, String fileToDownload){
 
  props = new Properties();
  StandardFileSystemManager manager = new StandardFileSystemManager();
 
  try {
 
   props.load(new FileInputStream("properties/" + propertiesFilename));
   String serverAddress = props.getProperty("serverAddress").trim();
   String userId = props.getProperty("userId").trim();
   String password = props.getProperty("password").trim();
   String remoteDirectory = props.getProperty("remoteDirectory").trim();
   String localDirectory = props.getProperty("localDirectory").trim();
 
    
   //Initializes the file manager
   manager.init();
    
   //Setup our SFTP configuration
   FileSystemOptions opts = new FileSystemOptions();
   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
     opts, "no");
   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
    
   //Create the SFTP URI using the host name, userid, password,  remote path and file name
   String sftpUri = "sftp://" + userId + ":" + password +  "@" + serverAddress + "/" + 
     remoteDirectory + fileToDownload;
    
   // Create local file object
   String filepath = localDirectory +  fileToDownload;
   File file = new File(filepath);
   FileObject localFile = manager.resolveFile(file.getAbsolutePath());
 
   // Create remote file object
   FileObject remoteFile = manager.resolveFile(sftpUri, opts);
 
   // Copy local file to sftp server
   localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
   System.out.println("File download successful");
 
  }
  catch (Exception ex) {
   ex.printStackTrace();
   return false;
  }
  finally {
   manager.close();
  }
 
  return true;
 }
 
}

Delete a file on remote server using SFTP使用 SFTP 删除远程服务器上的文件

import java.io.FileInputStream;
import java.util.Properties;
 
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
 
public class DeleteRemoteFile {
 
 static Properties props;
 
 public static void main(String[] args) {
 
  DeleteRemoteFile getMyFiles = new DeleteRemoteFile();
  if (args.length < 1)
  {
   System.err.println("Usage: java " + getMyFiles.getClass().getName()+
   " Properties_filename File_To_Delete ");
   System.exit(1);
  }
 
  String propertiesFilename = args[0].trim();
  String fileToDownload = args[1].trim();
  getMyFiles.startFTP(propertiesFilename, fileToDownload);
    
 }
 
 public boolean startFTP(String propertiesFilename, String fileToDownload){
 
  props = new Properties();
  StandardFileSystemManager manager = new StandardFileSystemManager();
 
  try {
 
   props.load(new FileInputStream("properties/" + propertiesFilename));
   String serverAddress = props.getProperty("serverAddress").trim();
   String userId = props.getProperty("userId").trim();
   String password = props.getProperty("password").trim();
   String remoteDirectory = props.getProperty("remoteDirectory").trim();
    
    
   //Initializes the file manager
   manager.init();
    
   //Setup our SFTP configuration
   FileSystemOptions opts = new FileSystemOptions();
   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
     opts, "no");
   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
    
   //Create the SFTP URI using the host name, userid, password,  remote path and file name
   String sftpUri = "sftp://" + userId + ":" + password +  "@" + serverAddress + "/" + 
     remoteDirectory + fileToDownload;
    
   //Create remote file object
   FileObject remoteFile = manager.resolveFile(sftpUri, opts);
 
   //Check if the file exists
   if(remoteFile.exists()){
    remoteFile.delete();
    System.out.println("File delete successful");
   }
   
  }
  catch (Exception ex) {
   ex.printStackTrace();
   return false;
  }
  finally {
   manager.close();
  }
 
  return true;
 }
 
}

hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements) hierynomus/sshj有一个完整的 SFTP 第 3 版实现(OpenSSH 实现的)

Example code from SFTPUpload.java SFTPUpload.java 中的示例代码

package net.schmizz.sshj.examples;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;

import java.io.File;
import java.io.IOException;

/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {

    public static void main(String[] args)
            throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.loadKnownHosts();
        ssh.connect("localhost");
        try {
            ssh.authPublickey(System.getProperty("user.name"));
            final String src = System.getProperty("user.home") + File.separator + "test_file";
            final SFTPClient sftp = ssh.newSFTPClient();
            try {
                sftp.put(new FileSystemFile(src), "/tmp");
            } finally {
                sftp.close();
            }
        } finally {
            ssh.disconnect();
        }
    }

}

JSch library is the powerful library that can be used to read file from SFTP server. JSch 库是功能强大的库,可用于从 SFTP 服务器读取文件。 Below is the tested code to read file from SFTP location line by line下面是从 SFTP 位置逐行读取文件的测试代码

JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("user", "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;

            InputStream stream = sftpChannel.get("/usr/home/testfile.txt");
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }

            } catch (IOException io) {
                System.out.println("Exception occurred during reading file from SFTP server due to " + io.getMessage());
                io.getMessage();

            } catch (Exception e) {
                System.out.println("Exception occurred during reading file from SFTP server due to " + e.getMessage());
                e.getMessage();

            }

            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }

Please refer the blog for whole program.请参阅博客了解整个程序。

Andy,要删除远程系统上的文件,您需要使用 JSch 的(channelExec)并传递 unix/linux 命令来删除它。

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".虽然上面的答案非常有帮助,但我花了一天时间让它们工作,面临各种异常,如“损坏的通道”、“rsa 密钥未知”和“数据包损坏”。

Below is a working reusable class for SFTP FILES UPLOAD/DOWNLOAD using JSch library.下面是一个使用 JSch 库的 SFTP 文件上传/下载的可重用类。

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

我使用 JSCH API http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/在 java 中找到了 SFTP 的完整工作示例

Try edtFTPj/PRO , a mature, robust SFTP client library that supports connection pools and asynchronous operations.尝试edtFTPj/PRO ,这是一个成熟、强大的 SFTP 客户端库,支持连接池和异步操作。 Also supports FTP and FTPS so all bases for secure file transfer are covered.还支持 FTP 和 FTPS,因此涵盖了安全文件传输的所有基础。

I use this SFTP API called Zehon, it's great, so easy to use with a lot of sample code.我使用这个名为 Zehon 的 SFTP API,它非常棒,使用大量示例代码非常容易使用。 Here is the site http://www.zehon.com这是网站http://www.zehon.com

您还拥有带有 SFTP 附加组件的 JFileUpload(Java 也是): http ://www.jfileupload.com/products/sftp/index.html

The best solution I've found is Paramiko .我找到的最好的解决方案是Paramiko There's a Java version.有一个Java版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM