org.yes.tools.build.utils.SFTPChannel Maven / Gradle / Ivy
package org.yes.tools.build.utils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.maven.plugin.logging.Log;
import org.yes.tools.build.bo.DeployBo;
/**
* @author Co.
* @name SFTPChannel
* @date 2023/9/14 11:33
*/
public class SFTPChannel {
Session session = null;
Channel channel = null;
//登录sftp
public ChannelSftp getChannel(DeployBo.Remote remote, Log log) {
try {
//创建JSch对象
JSch jsch = new JSch();
//根据用户名,主机ip,端口获取一个Session对象
session = jsch.getSession(remote.getUsername(), remote.getRemoteHost(), remote.getRemotePort());
session.setConfig("StrictHostKeyChecking", "no");
// 密码认证
session.setPassword(remote.getPassword());
// 建立session
session.connect(10000);
// 打开SFTP通道
channel = session.openChannel("sftp");
channel.connect(); // 建立SFTP通道的连接
log.debug("Connected successfully to ftpHost = " + remote.getRemoteHost() + ",as ftpUserName = " + remote.getUsername()
+ ", returning: " + channel);
return (ChannelSftp) channel;
} catch (Exception e) {
throw new RuntimeException("sftp连接错误,host=" + remote.getRemoteHost() + ",userName=" + remote.getUsername() + ",port=" + remote.getRemoteHost() + ",pwd=" + remote.getPassword());
}
}
//退出sftp
public void closeChannel() throws Exception {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}