java sftp连接

package com.cpic.lifeplan.common.util;

import java.util.Properties;

import org.apache.log4j.Logger;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * 处理sftp工具类
 * @author 严程
 */
public class  SftpUtil {
	protected  Logger log = Logger.getLogger(SftpUtil.class);
	private Session session  = null;
    private ChannelSftp sftp = null; 
    /**
	 * 打开sftp并连接
	 * @return
	 * @throws JSchException 
	 * @throws Exception
	 */
	public ChannelSftp getSftp(){
		try {
			String username = ConfigUtil.getConfigValue(ConfigUtil.USERNAME);
			String host = ConfigUtil.getConfigValue(ConfigUtil.HOST);
			int port = Integer.parseInt(ConfigUtil.getConfigValue(ConfigUtil.PORT));
			String password = ConfigUtil.getConfigValue(ConfigUtil.PASSWORD);
			JSch jsch = new JSch();
			session = jsch.getSession(username, host, port);
			session.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			session.setConfig(sshConfig);
			session.connect();
			sftp = (ChannelSftp)session.openChannel("sftp");
			sftp.connect();
		} catch (JSchException e) {
			if (sftp != null) {
				sftp.disconnect();
				sftp = null;
			}
			if (session != null) {
				session.disconnect();
				session = null;
			}
			log.error("系统异常sftp连接失败!",e);
		}
		return sftp;
	}
	
	/**
	 * 关闭连接;
	 */
	public void close() {
		if (sftp != null) {
			sftp.disconnect();
			sftp = null;
		}
		if (session != null) {
			session.disconnect();
			session = null;
		}
	}

}

你可能感兴趣的:(java)