Reliable example of how to use SFTP using public private key authentication with Java

前端 未结 3 893
生来不讨喜
生来不讨喜 2021-01-31 05:41

Recently a client of our unexpectedly shifted some important files we collect from an ftp to sftp server. Initially I was under the impression that it would be simple to write

3条回答
  •  伪装坚强ぢ
    2021-01-31 06:12

    I guess this is what you are looking for -

    /**
    * @param args
    */
    public static void main(String[] args) {
    
        /*Below we have declared and defined the SFTP HOST, PORT, USER
                and Local private key from where you will make connection */
        String SFTPHOST = "10.20.30.40";
        int    SFTPPORT = 22;
        String SFTPUSER = "kodehelp";
        // this file can be id_rsa or id_dsa based on which algorithm is used to create the key
        String privateKey = "/home/kodehelp/.ssh/id_rsa";
        String SFTPWORKINGDIR = "/home/kodehelp/";
    
        JSch jSch = new JSch();
        Session     session     = null;
        Channel     channel     = null;
        ChannelSftp channelSftp = null;
        try {
            jSch.addIdentity(privateKey);
            System.out.println("Private Key Added.");
            session = jSch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
            System.out.println("session created.");
    
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("shell channel connected....");
            channelSftp = (ChannelSftp)channel;
            channelSftp.cd(SFTPWORKINGDIR);
            System.out.println("Changed the directory...");
        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SftpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(channelSftp!=null){
                channelSftp.disconnect();
                channelSftp.exit();
            }
            if(channel!=null) channel.disconnect();
    
            if(session!=null) session.disconnect();
        }
    }
    

    See more at

    http://kodehelp.com/sftp-connection-public-key-authentication-java/

提交回复
热议问题