import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; /** * @description SFTP工具 * @author Luxh */ public class SFTPUtils { private static final Logger Log = LoggerFactory.getLogger(SFTPUtils.class); /**FTP协议*/ private static final String FTP_PROTOCOL = "sftp"; /** * 获取session * @param host * @param port * @param username * @param password * @return */ public static Session getSession(String host, int port, String username, String password) { Session session = null; try { Log.info("init session..."); JSch jsch = new JSch(); session = jsch.getSession(username, host, port); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Log.info("init session successful"); }catch(Exception e) { Log.error("init session failed"); } return session; } /** * 获取 ChannelSftp * @param session * @return */ public static ChannelSftp getChannelSftp(Session session){ ChannelSftp sftp = null; try{ Log.info("init ChannelSftp..."); Channel channel = session.openChannel(FTP_PROTOCOL); channel.connect(); sftp = (ChannelSftp) channel; Log.info("init ChannelSftp successful"); }catch(Exception e) { Log.error("init ChannelSftp failed"); } return sftp; } /** * 上传 * @param src 源文件路径 * @param dst 目标文件路径 * @param sftp */ public static void upload(String src, String dst, ChannelSftp sftp) { try { Log.info("begin upload..."); Log.info("src file is:{}", src); Log.info("dst file is:{}", dst); sftp.put(src, dst); Log.info("upload successful"); } catch (Exception e) { Log.error("upload failed"); } } /** * 下载 * @param src 要下载的文件 * @param dst 存放路径 * @param sftp */ public static void download(String src, String dst, ChannelSftp sftp) { try { Log.info("begin download..."); Log.info("src file is:{} ", src); Log.info("dst file is:{} ", dst); sftp.get(src, dst); Log.info("download successful"); } catch (Exception e) { Log.error("download failed"); } } /** * 删除 * @param path 要删除的文件路径 * @param sftp */ public static void delete(String path, ChannelSftp sftp) { try { Log.info("begin delete..."); Log.info("dst file is: {}", path); sftp.rm(path); Log.info("delete successful"); } catch (Exception e) { Log.error("delete failed"); } } /** * 关闭连接 * @param session * @param sftp */ public static void close(Session session, ChannelSftp sftp){ if(sftp != null) { sftp.disconnect(); Log.info("ChannelSftp disconnect"); } if(session != null) { session.disconnect(); Log.info("Session disconnect"); } } }
使用了jsch库:http://www.jcraft.com/jsch/