您的位置:首页 > 编程语言 > PHP开发

SFTP客户端连接

2017-08-04 15:22 162 查看
最近项目使用SFTP很多,在使用过程中遇到很多问题,把自己用到的和同事指导后的代码整理出发,记录一下:

需要引用的jar:

jsch-0.1.53.jar

SFTPClient类:

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);
}

}


StringUtils工具类:

public class StringUtils {

/**
* 判断字符串是否为空,为空返回true
*/
public static boolean isEmpty(String str) {
return (str == null || "".equals(str.trim()) || "null".equals(str
.trim()));
}

}


IOUtils工具类:
public class IOUtils extends org.apache.commons.io.IOUtils{
public static void closeQuietly(Session session){
if (session != null) {
session.disconnect();
}
}

public static void closeQuietly(Channel channel){
if (channel != null) {
channel.disconnect();
}
}

}


SFTP使用过程完要记得关闭相应的会话session和通道channel,避免连接过多导致不能创建新的SFTP连接,代码仅供参考,
有不对的请包涵和指正
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVA SFTP