1 packagecom.snow.sftp;2
3 importcom.jcraft.jsch.Channel;4 importcom.jcraft.jsch.ChannelSftp;5 importcom.jcraft.jsch.JSch;6 importcom.jcraft.jsch.JSchException;7 importcom.jcraft.jsch.Session;8 importcom.jcraft.jsch.SftpException;9 importlombok.extern.slf4j.Slf4j;10 importorg.springframework.stereotype.Service;11
12 importjava.util.Properties;13
14 @Slf4j15 @Service(value = "sftpService")16 public class SftpServiceImpl implementsSftpService {17
18 privateSession session;19 privateChannel channel;20 privateChannelSftp channelSftp;21
22 @Override23 public voidcreateChannel(SftpAuthority sftpAuthority) {24 try{25 JSch jSch = newJSch();26 session =jSch.getSession(sftpAuthority.getUser(), sftpAuthority.getHost(), sftpAuthority.getPort());27
28 if (sftpAuthority.getPassword() != null) {29 //使用用户名密码创建SSH
30 session.setPassword(sftpAuthority.getPassword());31 } else if (sftpAuthority.getPrivateKey() != null) {32 //使用公私钥创建SSH
33 jSch.addIdentity(sftpAuthority.getPrivateKey(), sftpAuthority.getPassphrase());34 }35
36 Properties properties = newProperties();37 properties.put("StrictHostKeyChecking", "no"); //主动接收ECDSA key fingerprint,不进行HostKeyChecking
38 session.setConfig(properties);39 session.setTimeout(0); //设置超时时间为无穷大
40 session.connect(); //通过session建立连接
41
42 channel = session.openChannel("sftp"); //打开SFTP通道
43 channel.connect();44 channelSftp =(ChannelSftp) channel;45 } catch(JSchException e) {46 log.error("create sftp channel failed!", e);47 }48 }49
50 @Override51 public voidcloseChannel() {52 if (channel != null) {53 channel.disconnect();54 }55
56 if (session != null) {57 session.disconnect();58 }59 }60
61 @Override62 public booleanuploadFile(SftpAuthority sftpAuthority, String src, String dst) {63 if (channelSftp == null) {64 log.warn("need create channelSftp before upload file");65 return false;66 }67
68 if(channelSftp.isClosed()) {69 createChannel(sftpAuthority); //如果被关闭则应重新创建
70 }71
72 try{73 channelSftp.put(src, dst, ChannelSftp.OVERWRITE);74 log.info("sftp upload file success! src: {}, dst: {}", src, dst);75 return true;76 } catch(SftpException e) {77 log.error("sftp upload file failed! src: {}, dst: {}", src, dst, e);78 return false;79 }80 }81
82 @Override83 public booleanremoveFile(SftpAuthority sftpAuthority, String dst) {84 if (channelSftp == null) {85 log.warn("need create channelSftp before remove file");86 return false;87 }88
89 if(channelSftp.isClosed()) {90 createChannel(sftpAuthority); //如果被关闭则应重新创建
91 }92
93 try{94 channelSftp.rm(dst);95 log.info("sftp remove file success! dst: {}", dst);96 return true;97 } catch(SftpException e) {98 log.error("sftp remove file failed! dst: {}", dst, e);99 return false;100 }101 }102
103 }