java连接并登录登出SFTP服务器(2)---免密登录sftp

java连接并免密登录SFTP服务器
pubKeyPath 为本地免密访问远程服务器配置的私钥的路径

@Service
public class FtpUtil {

    public static ThreadLocal channelSftpMap = new ThreadLocal();
    
/**
     * 连接并登录SFTP服务器(免密登录)
     * @param hostname FTP地址
     * @param username FTP登录用户
     * @param pubKeyPath 指定本机的私钥的路径
     * @param timeout  超时时间,单位ms,it use java.net.Socket.setSoTimeout(timeout) 
     * @return True if successfully completed, false if not.
     */
    public  boolean loginSFTP(String hostname, int port, String username, String pubKeyPath, int timeout){
        ChannelSftp channelSftp = channelSftpMap.get();
        if(null!=channelSftp && channelSftp.isConnected()){
            return true;
        }
        channelSftpMap.remove();
        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        channelSftp = null;
        try {
            session = jsch.getSession(username, hostname, port);
        } catch (JSchException e) {
            logger.warn("SFTP Server[" + hostname + "] Session created failed,堆栈轨迹如下", e);
            return false;
        }
        try {
            jsch.addIdentity(pubKeyPath);
        } catch (JSchException e1) {
            logger.warn("SFTP Server[" + hostname + "] Session connected failed,堆栈轨迹如下", e1);
            e1.printStackTrace();
        }
        //Security.addProvider(new com.sun.crypto.provider.SunJCE());
        //Setup Strict HostKeyChecking to no so we dont get the unknown host key exception
        session.setConfig("StrictHostKeyChecking", "no");
        try {
            session.setTimeout(timeout);
            session.connect();
        } catch (Exception e) {
            logger.warn("SFTP Server[" + hostname + "] Session connected failed,堆栈轨迹如下", e);
            return false;
        }
        try {
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp)channel;
            channelSftpMap.set(channelSftp);
            logger.warn("SFTP Server[" + hostname + "] connected success...当前所在目录为" + channelSftp.pwd());
            return true;
        } catch (Exception e) {
            logger.warn("SFTP Server[" + hostname + "] Opening FTP Channel failed,堆栈轨迹如下", e);
            return false;
        }
    }

}

你可能感兴趣的:(java)