1. 程式人生 > >SFTP客戶端連線

SFTP客戶端連線

public class SFTPClient {
    private static final Logger logger = Logger.getLogger(SFTPClient.class);

    private static int timeoutSecond = 20;
    private Session session;
    private ChannelSftp channel;

    private SFTPClient(Session session, ChannelSftp channel) {
        this.session = session;
        this.channel = channel;
    }

    public static final SFTPClient connect(String ip, int port, String userName, String password) throws Exception {
        if (StringUtils.isEmpty(ip)||StringUtils.isEmpty(userName)||StringUtils.isEmpty(password)) {
			throw new Exception("連線SFTP引數異常");
		}
        Session session = null;
        Channel channel = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(userName, ip, port);
            session.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect(timeoutSecond * 1000);
            logger.info(" Sftp connect success");
            return new SFTPClient(session, (ChannelSftp) channel);
        } catch (JSchException e) {
            logger.error(" Sftp connect error : ", e);
            IOUtils.closeQuietly(channel);
            IOUtils.closeQuietly(session);
            throw new Exception(" Sftp connect error : "+e.getMessage());
        }
    }

    public void close() {
    	IOUtils.closeQuietly(channel);
        IOUtils.closeQuietly(session);
    }
    
    

}