JSch包maven倉庫地址:
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency>
sftp 上傳下載工具類
package wenjun.zhang.jsch; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.SftpException; /** * sftp 上傳下載工具類 */ public class SftpUtil { private static Logger logger = LoggerFactory.getLogger(SftpUtil.class); /** * 獲取Sftp對象 * @param param * @return */ public static SftpConfig getSftpObj(String param) { SftpConfig sftpConfig = new SftpConfig(); if (StringUtils.isNotBlank(param)) { JSONObject jsonObj = JSONObject.fromObject(param); sftpConfig = (SftpConfig) JSONObject.toBean(jsonObj, SftpConfig.class); } return sftpConfig; } /** sftp 上傳*/ public static boolean upload(SftpConfig config, String baseDir, String fileName, String filePath) { logger.info("路徑:baseDir="+baseDir); SftpChannel sftpChannel = new SftpChannel(); ChannelSftp sftp = null; try { if (StringUtils.isNotBlank(config.getPrivateKeyPath())) { sftp = sftpChannel.connectByIdentity(config); } else { sftp = sftpChannel.connectByPwd(config); } if (sftp.isConnected()) { logger.info("連接服務器成功"); } else { logger.error("連接服務器失敗"); return false; } //檢查路徑 if(!isExist(sftp, baseDir)){ logger.error("創建sftp服務器路徑失敗:" + baseDir); return false; } String dst = baseDir + "/" + fileName; String src = filePath + "/" + fileName; logger.info("開始上傳,本地服務器路徑:["+src +"]目標服務器路徑:["+dst+"]"); sftp.put(src, dst); logger.info("上傳成功"); return true; } catch (Exception e) { logger.error("上傳失敗", e); return false; } finally { sftpChannel.closeChannel(); } } /**sftp 下載 */ public static boolean down(SftpConfig config, String baseDir, String fileName1, String filePath, String fileName2 ) { SftpChannel sftpChannel = new SftpChannel(); ChannelSftp sftp = null; try { if (StringUtils.isNotBlank(config.getPrivateKeyPath())) { sftp = sftpChannel.connectByIdentity(config); } else { sftp = sftpChannel.connectByPwd(config); } if (sftp.isConnected()) { logger.info("連接服務器成功"); } else { logger.error("連接服務器失敗"); return false; } String dst = ""; if (StringUtils.isBlank(fileName2)) { dst = filePath + fileName1; } else{ dst = filePath + fileName2; } String src = baseDir+ "/" + fileName1; logger.info("開始下載,sftp服務器路徑:["+src +"]目標服務器路徑:["+dst+"]"); sftp.get(src, dst); logger.info("下載成功"); return true; } catch (Exception e) { logger.error("下載失敗", e); return false; } finally { sftpChannel.closeChannel(); } } /** * 判斷文件夾是否存在 * true 目錄創建成功,false 目錄創建失敗 * @param sftp * @param filePath 文件夾路徑 * @return */ public static boolean isExist(ChannelSftp sftp, String filePath) { String paths[] = filePath.split("\\/"); String dir = paths[0]; for (int i = 0; i < paths.length - 1; i++) { dir = dir + "/" + paths[i + 1]; try{ sftp.cd(dir); }catch(SftpException sException){ if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){ try { sftp.mkdir(dir); } catch (SftpException e) { e.printStackTrace(); return false; } } } } return true; } }
SftpChannel sftp連接
package wenjun.zhang.jsch; import java.util.Properties; import org.apache.commons.lang.StringUtils; 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; public class SftpChannel { Session session = null; Channel channel = null; //端口默認為22 public static final int SFTP_DEFAULT_PORT = 22; /** 利用JSch包實現SFTP下載、上傳文件(秘鑰方式登陸)*/ public ChannelSftp connectByIdentity(SftpConfig sftpConfig) throws JSchException { JSch jsch = new JSch(); int port = SFTP_DEFAULT_PORT; //設置密鑰和密碼 //支持密鑰的方式登陸,只需在jsch.getSession之前設置一下密鑰的相關信息就可以了 if (StringUtils.isNotBlank(sftpConfig.getPrivateKeyPath())) { if (StringUtils.isNotBlank(sftpConfig.getPassphrase())) { //設置帶口令的密鑰 jsch.addIdentity(sftpConfig.getPrivateKeyPath(), sftpConfig.getPassphrase()); } else { //設置不帶口令的密鑰 jsch.addIdentity(sftpConfig.getPrivateKeyPath()); } } if (sftpConfig.getPort() != null) { port = Integer.valueOf(sftpConfig.getPort()); } if (port > 0) { //采用指定的端口連接服務器 session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp(), port); } else { //連接服務器,采用默認端口 session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp()); } if (session == null) { throw new JSchException("session為空,連接失敗"); } Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); session.setConfig(sshConfig); session.setTimeout(30000); session.connect(); //創建sftp通信通道 channel = (Channel) session.openChannel("sftp"); channel.connect(); return (ChannelSftp) channel; } /** 利用JSch包實現SFTP下載、上傳文件(用戶名密碼方式登陸) */ public ChannelSftp connectByPwd(SftpConfig sftpConfig) throws JSchException { JSch jsch = new JSch(); int port = SFTP_DEFAULT_PORT; if (sftpConfig.getPort() != null) { port = Integer.valueOf(sftpConfig.getPort()); } if (port > 0) { //采用指定的端口連接服務器 session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp(), port); } else { //連接服務器,采用默認端口 session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp()); } if (session == null) { throw new JSchException("session為空,連接失敗"); } //設置登陸主機的密碼 session.setPassword(sftpConfig.getPwd());//設置密碼 Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); session.setConfig(sshConfig); session.setTimeout(30000); session.connect(); //創建sftp通信通道 channel = (Channel) session.openChannel("sftp"); channel.connect(); return (ChannelSftp) channel; } public void closeChannel() { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } }
sftp配置類
package wenjun.zhang.jsch; /** * sftp 配置 */ public class SftpConfig { /** 密鑰地址 */ private String privateKeyPath; /** 口令 */ private String passphrase; private String ip; private Integer port; private String username; private String pwd; private String path; private String baseDir; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getBaseDir() { return baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } public String getPrivateKeyPath() { return privateKeyPath; } public void setPrivateKeyPath(String privateKeyPath) { this.privateKeyPath = privateKeyPath; } public String getPassphrase() { return passphrase; } public void setPassphrase(String passphrase) { this.passphrase = passphrase; } }