JAVA实现上传文件到服务器、删除服务器文件

时间:2023-03-09 21:22:08
JAVA实现上传文件到服务器、删除服务器文件

使用的jar包:

 <dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

文件上传也可以使用scp,但是最后实现发现scp特别困难,而且只能实现上传这一个功能。如果要实现文件的删除则需要使用其他命令。

而sftp则是建立一个ssh通道,然后可以很方便的在通道内执行一系列命令,如put, get, rm, mkdir, rmdir,从而可以方便的管理远程服务器的文件。

下面介绍下Java实现。

首先我们创建一个pojo,将所有的账号信息及远程服务器信息都封装一下。

 package com.snow.sftp;

 import lombok.Data;

 @Data
public class SftpAuthority {
private String host; // 服务器ip或者主机名
private int port; // sftp端口
private String user; // sftp使用的用户
private String password; // 账户密码
private String privateKey; // 私钥文件名
private String passphrase; // 私钥密钥 public SftpAuthority(String user, String host, int port) {
this.host = host;
this.port = port;
this.user = user;
}
}

在建立sftp通道过程中我们可以选择使用用户名密码的方式,也可以选择使用私钥(私钥可以有密钥)的方式。

建立一个service interface

 package com.snow.sftp;

 public interface SftpService {

     void createChannel(SftpAuthority sftpAuthority);

     void closeChannel();

     boolean uploadFile(SftpAuthority sftpAuthority, String src, String dst);

     boolean removeFile(SftpAuthority sftpAuthority, String dst);

 }

具体实现:

 package com.snow.sftp;

 import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import java.util.Properties; @Slf4j
@Service(value = "sftpService")
public class SftpServiceImpl implements SftpService { private Session session;
private Channel channel;
private ChannelSftp channelSftp; @Override
public void createChannel(SftpAuthority sftpAuthority) {
try {
JSch jSch = new JSch();
session = jSch.getSession(sftpAuthority.getUser(), sftpAuthority.getHost(), sftpAuthority.getPort()); if (sftpAuthority.getPassword() != null) {
// 使用用户名密码创建SSH
session.setPassword(sftpAuthority.getPassword());
} else if (sftpAuthority.getPrivateKey() != null) {
// 使用公私钥创建SSH
jSch.addIdentity(sftpAuthority.getPrivateKey(), sftpAuthority.getPassphrase());
} Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no"); // 主动接收ECDSA key fingerprint,不进行HostKeyChecking
session.setConfig(properties);
session.setTimeout(0); // 设置超时时间为无穷大
session.connect(); // 通过session建立连接 channel = session.openChannel("sftp"); // 打开SFTP通道
channel.connect();
channelSftp = (ChannelSftp) channel;
} catch (JSchException e) {
log.error("create sftp channel failed!", e);
}
} @Override
public void closeChannel() {
if (channel != null) {
channel.disconnect();
} if (session != null) {
session.disconnect();
}
} @Override
public boolean uploadFile(SftpAuthority sftpAuthority, String src, String dst) {
if (channelSftp == null) {
log.warn("need create channelSftp before upload file");
return false;
} if (channelSftp.isClosed()) {
createChannel(sftpAuthority); // 如果被关闭则应重新创建
} try {
channelSftp.put(src, dst, ChannelSftp.OVERWRITE);
log.info("sftp upload file success! src: {}, dst: {}", src, dst);
return true;
} catch (SftpException e) {
log.error("sftp upload file failed! src: {}, dst: {}", src, dst, e);
return false;
}
} @Override
public boolean removeFile(SftpAuthority sftpAuthority, String dst) {
if (channelSftp == null) {
log.warn("need create channelSftp before remove file");
return false;
} if (channelSftp.isClosed()) {
createChannel(sftpAuthority); // 如果被关闭则应重新创建
} try {
channelSftp.rm(dst);
log.info("sftp remove file success! dst: {}", dst);
return true;
} catch (SftpException e) {
log.error("sftp remove file failed! dst: {}", dst, e);
return false;
}
} }

调用示例:

 package com.snow.sftp;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSftp { public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"sftp-application-context.xml"}); // 用户名密码方式
SftpService sftpService = context.getBean(SftpService.class);
SftpAuthority sftpAuthority = new SftpAuthority("user", "ip or host", port);
sftpAuthority.setPassword("user password"); sftpService.createChannel(sftpAuthority);
sftpService.uploadFile(sftpAuthority, "/home/snow/test/test.png", "/user/testaaa.png");
sftpService.removeFile(sftpAuthority, "/user/testaaa.png");
sftpService.closeChannel(); // 公私钥方式
sftpAuthority = new SftpAuthority("user", "ip or host", port);
sftpAuthority.setPrivateKey("your private key full path");
sftpAuthority.setPassphrase("private key passphrase");
sftpService.createChannel(sftpAuthority);
sftpService.uploadFile(sftpAuthority, "/home/snow/test/test.png", "/user/testaaa.png");
sftpService.removeFile(sftpAuthority, "/user/testaaa.png");
sftpService.closeChannel();
} }

除了本文介绍的put和rm操作以外,channelSftp还有很多其它的操作,比如get, mkdir, lcd, rename, rmdir, ls, lstat等,大家可以自行探索。