scp via java

前端 未结 15 983
粉色の甜心
粉色の甜心 2020-11-27 13:06

What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libr

15条回答
  •  粉色の甜心
    2020-11-27 13:37

    jsCH has worked great for me. Below is an example of a method that will connect to sftp server and download files to specified directory. It is recommended to stay away from disabling StrictHostKeyChecking. Although a little bit more difficult to set up, for security reasons specifying the known hosts should be the norm.

    jsch.setKnownHosts("C:\Users\test\known_hosts"); recommended

    JSch.setConfig("StrictHostKeyChecking", "no"); - not recommended

    import com.jcraft.jsch.*;
     public void downloadFtp(String userName, String password, String host, int port, String path) {
    
    
            Session session = null;
            Channel channel = null;
            try {
                JSch ssh = new JSch();
                JSch.setConfig("StrictHostKeyChecking", "no");
                session = ssh.getSession(userName, host, port);
                session.setPassword(password);
                session.connect();
                channel = session.openChannel("sftp");
                channel.connect();
                ChannelSftp sftp = (ChannelSftp) channel;
                sftp.get(path, "specify path to where you want the files to be output");
            } catch (JSchException e) {
                System.out.println(userName);
                e.printStackTrace();
    
    
            } catch (SftpException e) {
                System.out.println(userName);
                e.printStackTrace();
            } finally {
                if (channel != null) {
                    channel.disconnect();
                }
                if (session != null) {
                    session.disconnect();
                }
            }
    
        }
    

提交回复
热议问题