java连接并登录登出SFTP服务器(1)

@Service
public class FtpUtil {

    public static ThreadLocal channelSftpMap = new ThreadLocal();
    
    private String hostname;
    private String username;
    private String password;
    private int port;

    public String getHostname() {
        return hostname;
    }
    public void setHostname(String hostname) {
        this.hostname = hostname;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    
/**
     * 连接并登录SFTP服务器
     * @param hostname FTP地址
     * @param username FTP登录用户
     * @param password FTP登录密码
     * @param timeout  超时时间,单位ms,it use java.net.Socket.setSoTimeout(timeout) 
     * @return True if successfully completed, false if not.
     */
    public  boolean loginViaSFTP(String hostname, int port, String username, String password, 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;
        }
        session.setPassword(password);
        //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;
        }
    }

/**
     * 登出SFTP服务器
     * @see 由于FtpUtil会自动维护ChannelSftp,故调用该方法便可直接登出SFTP
     */
    public  void logoutViaSFTP(){
        ChannelSftp channelSftp = channelSftpMap.get();
        channelSftpMap.remove();
        String hostname = null;
        try {
            hostname = channelSftp.getHome();
            if(null != channelSftp){
                channelSftp.quit();
            }
            if(null != channelSftp.getSession()){
                channelSftp.getSession().disconnect();
            }
        } catch (Exception e) {
            logger.warn("Unable to disconnect from SFTP server[" + hostname + "]", e);
        }
    }

}

1.登出时要注意ftpClient.disconnect()的时机,ftpClient.logout()也会抛异常
  所要注意避免FTPClient对象退出异常,连接没有释放,最后积少成多直至阻塞FTP服务器的连接,进而引发连接异常
2.FTP response 421 received.  Server closed connection.
  这个错误的原因就是FTP服务器端连接数满了
3.Connection closed without indication.
  这个错误的原因就是FTP服务器端发生故障或者网络出现问题

你可能感兴趣的:(java)