1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| import com.jcraft.jsch.*; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component;
import java.util.Properties;
/** * sftp配置 * * @author zhujx * @date 2021/03/02 18:22 */ @Slf4j @Data @Component @ConfigurationProperties(prefix = "sftp.server") public class SftpConfig {
/** * host */ private String host;
/** * 端口 */ private Integer port;
/** * 账号 */ private String username;
/** * 密码 */ private String password;
/** * 根目录 */ private String rootPath;
private ChannelSftp channel;
private Session session;
private void connectServer() throws JSchException { // 创建JSch对象 JSch jsch = new JSch(); // 根据用户名,主机ip,端口获取一个Session对象 session = jsch.getSession(username, host, port); session.setPassword(password); Properties configTemp = new Properties(); configTemp.put("StrictHostKeyChecking", "no"); // 为Session对象设置properties session.setConfig(configTemp); // 设置timeout时间 session.setTimeout(60000); session.connect(); // 通过Session建立链接 // 打开SFTP通道 channel = (ChannelSftp) session.openChannel("sftp"); // 建立SFTP通道的连接 channel.connect(); }
/** * 断开SFTP Channel、Session连接 */ private void closeChannel() { try { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } catch (Exception e) { log.info("sftp close error", e); } }
/** * 上传文件 * * @param localPath 本地文件 * @param remotePath 远程文件 */ public void upload(String localPath, String remotePath) { log.info("localPath {}", localPath); log.info("remotePath {}", remotePath); try { connectServer(); channel.put(localPath, remotePath, ChannelSftp.OVERWRITE); channel.quit(); } catch (SftpException e) { log.info("sftp upload error", e); } catch (JSchException e) { log.info("sftp open error", e); } finally { closeChannel(); } }
/** * 下载文件 * * @param remotePath 远程文件 * @param localPath 本地文件 */ public void download(String remotePath, String localPath) throws Exception { log.info("remotePath {}", remotePath); log.info("localPath {}", localPath); try { connectServer(); channel.get(remotePath, localPath); channel.quit(); } finally { closeChannel(); } }
|