使用jsch Jar实现SFTP上传、下载、创建、删除文件(文末附代码)
2.1 SFTP是什么?
- SFTP = SSH + FTP,也就是安全的网络文件传输协议;
- SSH是一种网络协议,主要用于远程登录,有两种等方式即 口令登录(账号、密码)、公钥登录(RSA)、两种方式;
- SSH应用场景: git代码拉取、提交;SFTP文件上传,下载;
2.2 文件传输
2.2.1 导入相关依赖
<!-- 在maven项目pom.xml中导入如下的坐标 -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2.2.2 创建SFTP连接
方式一:用户密码方式
/**
* 创建SFTP连接
* @return
* @throws Exception
*/
private ChannelSftp createSftp() throws Exception {
JSch jsch = new JSch();
log.info("Try to connect sftp[" + config.getUsername() + "@" + config.getHost() + "], use password[" + config.getPassword() + "]");
Session session = createSession(jsch, config.getHost(), config.getUsername(), config.getPort());
session.setPassword(config.getPassword());
session.connect(config.getSessionConnectTimeout());
log.info("Session connected to {}.", config.getHost());
Channel channel = session.openChannel(config.getProtocol());
channel.connect(config.getChannelConnectedTimeout());
log.info("Channel created to {}.", config.getHost());
return (ChannelSftp) channel;
}
方式二:秘钥对方式登陆
/**
* 加密秘钥方式登陆
* @return
*/
private ChannelSftp connectByKey() throws Exception {
JSch jsch = new JSch();
// 设置密钥和密码 ,支持密钥的方式登陆
if (StringUtils.isNotBlank(config.getPrivateKey())) {
if (StringUtils.isNotBlank(config.getPassphrase())) {
// 设置带口令的密钥
jsch.addIdentity(config.getPrivateKey(), config.getPassphrase());
} else {
// 设置不带口令的密钥
jsch.addIdentity(config.getPrivateKey());
}
}
log.info("Try to connect sftp[" + config.getUsername() + "@" + config.getHost() + "], use private key[" + config.getPrivateKey()
+ "] with passphrase[" + config.getPassphrase() + "]");
Session session = createSession(jsch, config.getHost(), config.getUsername(), config.getPort());
// 设置登陆超时时间
session.connect(config.getSessionConnectTimeout());
log.info("Session connected to " + config.getHost() + ".");
// 创建sftp通信通道
Channel channel = session.openChannel(config.getProtocol());
channel.connect(config.getChannelConnectedTimeout());
log.info("Channel created to " + config.getHost() + ".");
return (ChannelSftp) channel;
}
2.3 上传下载
ChannelSftp channelSftp= this.createSftp();
// 上传文件
channelSftp.put(localFile, remoteFile);
// 下载文件
channelSftp.get(remoteFile, localFile);