-
原 sftp 工具类2015-11-18 15:47:35 jcy7523 阅读数 0
-
-
【直通华为HCNA/HCNP系列S篇2】VRP系统使用、维护与...
全面介绍华为VRP系统的使用、维护与管理方法。主要包括(1)VRP系统的基本操作,(2)VRP软件系统组成与启动文件管理,(3)VRP系统软件和配置文件的备份、恢复方法配置与实验,(4)VRP系统登录:包括Console/MiniUSB口/Telnet/STelnet/HTTP和HTTPS登录方法配置与实验,(5)VRP文件系统管理:包括FTP/SFTP/SCP和FTPS设备访问方法配置与实验等。
48课时 886分钟 27944人学习 王达免费试看
/** * 创建于:2015年11月16日 上午10:34:19 * 所属项目: * 文件名称:SftpUtil.java * 作者:test * 版权信息: */ package sftp; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import org.apache.log4j.Logger; 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; public class SftpUtil { private static Logger logger = Logger.getLogger(SftpUtil.class); public static void main(String[] args) throws SftpException { SftpUtil sftpUtil = new SftpUtil(); ChannelSftp sftp = sftpUtil.connect("192.168.8.18", 22, "test", "test"); //sftpUtil.download("tomcat/logs", "localhost_access_log.2015-11-13.txt", "E:/manager.2015-11-18.log", sftp); //sftpUtil.upload("", "E:/pom.xml", sftp); sftpUtil.delete("tomcat/logs", "pom.xml", sftp); sftpUtil.disconnect(sftp); logger.info("完成了"); } /** * 连接sftp服务器 * @param host 主机 * @param port 端口 * @param username 用户名 * @param password 密码 * @return */ public ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); Session sshSession = jsch.getSession(username, host, port); sshSession.setPassword(password); Properties sshConfig = new Properties(); // 如果设置成“yes”,ssh就不会自动把计算机的密钥加入“$HOME/.ssh/known_hosts”文件 // 并且一旦计算机的密钥发生了变化,就拒绝连接 sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); Channel channel = sshSession.openChannel("sftp"); channel.connect(); logger.info("host:" + host + ",port:" + port + "连接成功"); sftp = (ChannelSftp) channel; } catch (Exception e) { e.printStackTrace(); } return sftp; } /** * 释放连接,关闭会话 * @param sftp ChannelSftp */ public void disconnect(ChannelSftp sftp){ if(sftp != null){ sftp.disconnect(); try { sftp.getSession().disconnect(); } catch (JSchException e) { e.printStackTrace(); } } } /** * 上传文件 * @param directory 上传的目录 * @param uploadFile 要上传的文件 * @param sftp ChannelSftp */ public void upload(String directory, String uploadFile, ChannelSftp sftp) { try { if(directory != null && !"".equals(directory)){ sftp.cd(directory); } File file = new File(uploadFile); FileInputStream fis = new FileInputStream(file); sftp.put(fis, file.getName()); fis.close(); logger.info(uploadFile + "上传成功"); } catch (Exception e) { e.printStackTrace(); } } /** * 下载文件 * @param directory 下载目录 * @param downloadFile 下载的文件 * @param saveFile 存在本地的路径 * @param sftp */ public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { try { if(directory != null && !"".equals(directory)){ sftp.cd(directory); } File file = new File(saveFile); FileOutputStream fos = new FileOutputStream(file); sftp.get(downloadFile, fos); fos.close(); logger.info(downloadFile + "下载完成"); } catch (Exception e) { e.printStackTrace(); } } /** * 删除文件 * @param directory 要删除文件所在目录 * @param deleteFile 要删除的文件 * @param sftp */ public void delete(String directory, String deleteFile, ChannelSftp sftp) { try { if(directory != null && !"".equals(directory)){ sftp.cd(directory); } sftp.rm(deleteFile); logger.info(deleteFile + "删除成功"); } catch (Exception e) { e.printStackTrace(); } } }
-
-
2019-01-17 08:46:15 ruixue0117 阅读数 888
-
-
【直通华为HCNA/HCNP系列S篇2】VRP系统使用、维护与...
全面介绍华为VRP系统的使用、维护与管理方法。主要包括(1)VRP系统的基本操作,(2)VRP软件系统组成与启动文件管理,(3)VRP系统软件和配置文件的备份、恢复方法配置与实验,(4)VRP系统登录:包括Console/MiniUSB口/Telnet/STelnet/HTTP和HTTPS登录方法配置与实验,(5)VRP文件系统管理:包括FTP/SFTP/SCP和FTPS设备访问方法配置与实验等。
48课时 886分钟 27944人学习 王达免费试看
jcraft包下载:https://download.csdn.net/download/ruixue0117/10922182
工具类用途针对Linux搭建文件服务器,上传和下载都使用文件流方式(使用Resquest和Response)。
功能包括:上传下载,批量上传下载,文件流上传(Request),下载写入文件流(Response),直接读取文件内容,直接写入文件,目录操作,文件删除。
SFtpUtils.java
package hh.com.util; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.ResourceBundle; import java.util.Vector; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; import hh.com.exception.CustomException; /** * SFTP工具类 * * @author xxx * @date 2019-1-17 * @version 1.0 */ public class SFtpUtils { private static Log logger = LogFactory.getLog(SFtpUtils.class); // FTP名称 private String ftpName; // FTP 登录用户名 private String username; // FTP 登录密码 private String password; // FTP 服务器地址IP地址 private String host; // FTP 端口 private int port; // 属性集 private ResourceBundle property = null; // 配置文件的路径名 private String configFile = "ftpconfig"; // 编码格式 private String encoding = "utf-8"; // 根目录 private String homeDir = "/ftp/fs01/"; private ChannelSftp sftp = null; private Session sshSession = null; public SFtpUtils(String ftpName) { this.ftpName = ftpName; setArg(configFile); } public static void main(String[] args) { SFtpUtils sftp = null; // 本地存放地址 String localPath = "E:\\logs\\"; // Sftp下载路径 String sftpPath = "/SFTP_FILES/TEST/"; try { sftp = new SFtpUtils("ATTACHMENT_"); sftp.uploadFile(new FileInputStream(new File(localPath + "logs.txt")), "logs.txt", sftpPath); sftp.downFile("/SFTP_FILES/TEST/", "logs.txt", "E:\\logs\\", "logs2.txt"); sftp.writeToFtp("/SFTP_FILES/TEST/logs1.txt", "有新的特殊订单待处理。"); StringBuffer sb = sftp.readFile("/SFTP_FILES/TEST/logs1.txt"); System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } } /** * 设置参数 * @param configFile 参数的配置文件 */ private void setArg(String configFile) { try { property = ResourceBundle.getBundle(configFile); username = property.getString(ftpName+"username"); password = property.getString(ftpName+"password"); host = property.getString(ftpName+"host"); port = Integer.parseInt(property.getString(ftpName+"port")); } catch (Exception e) { System.out.println("配置文件 " + configFile + " 无法读取!"); } } /** * 通过SFTP连接服务器 */ private void connect() { try { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); if (logger.isInfoEnabled()) { logger.info("Session created."); } sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); if (logger.isInfoEnabled()) { logger.info("Session connected."); } Channel channel = sshSession.openChannel("sftp"); channel.connect(); if (logger.isInfoEnabled()) { logger.info("Opening Channel."); } sftp = (ChannelSftp) channel; if (logger.isInfoEnabled()) { logger.info("Connected to " + host + "."); } } catch (Exception e) { e.printStackTrace(); } } /** * 关闭连接 */ private void disconnect() { if (this.sftp != null) { if (this.sftp.isConnected()) { this.sftp.disconnect(); if (logger.isInfoEnabled()) { logger.info("sftp is closed already"); } } } if (this.sshSession != null) { if (this.sshSession.isConnected()) { this.sshSession.disconnect(); if (logger.isInfoEnabled()) { logger.info("sshSession is closed already"); } } } } /** * 批量下载文件 * * @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/) * @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\) * @param fileFormat:下载文件格式(以特定字符开头,为空不做检验) * @param fileEndFormat:下载文件格式(文件格式) * @param del:下载后是否删除sftp文件 * @return */ public List<String> batchDownFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) { List<String> filenames = new ArrayList<String>(); boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } Vector v = listFiles(remotePath); if (v.size() > 0) { Iterator it = v.iterator(); while (it.hasNext()) { LsEntry entry = (LsEntry) it.next(); String filename = entry.getFilename(); SftpATTRS attrs = entry.getAttrs(); if (!attrs.isDir()) { boolean flag = false; String localFileName = localPath + filename; fileFormat = fileFormat == null ? "" : fileFormat.trim(); fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim(); // 三种情况 if (fileFormat.length() > 0 && fileEndFormat.length() > 0) { if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) { flag = downFile(remotePath, filename, localPath, filename); if (flag) { filenames.add(localFileName); if (flag && del) { deleteSFTP(remotePath, filename); } } } } else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) { if (filename.startsWith(fileFormat)) { flag = downFile(remotePath, filename, localPath, filename); if (flag) { filenames.add(localFileName); if (flag && del) { deleteSFTP(remotePath, filename); } } } } else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) { if (filename.endsWith(fileEndFormat)) { flag = downFile(remotePath, filename, localPath, filename); if (flag) { filenames.add(localFileName); if (flag && del) { deleteSFTP(remotePath, filename); } } } } else { flag = downFile(remotePath, filename, localPath, filename); if (flag) { filenames.add(localFileName); if (flag && del) { deleteSFTP(remotePath, filename); } } } } } } if (logger.isInfoEnabled()) { logger.info("download file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is" + v.size()); } } catch (SftpException e) { e.printStackTrace(); } finally { if (_flag) disconnect(); } return filenames; } /** * 下载单个文件 * * @param remotPath:远程下载目录(以路径符号结束) * @param remoteFileName:下载文件名 * @param localPath:本地保存目录(以路径符号结束) * @param localFileName:保存文件名 * @return */ public boolean downFile(String remotePath, String remoteFileName, String localPath, String localFileName) { FileOutputStream fieloutput = null; boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } File file = new File(localPath + localFileName); fieloutput = new FileOutputStream(file); sftp.get(homeDir + remotePath + remoteFileName, fieloutput); if (logger.isInfoEnabled()) { logger.info("DownloadFile:" + remoteFileName + " success from sftp."); } return true; } catch (Exception e) { e.printStackTrace(); } finally { if (null != fieloutput) { try { fieloutput.close(); } catch (IOException e) { e.printStackTrace(); } } if (_flag) disconnect(); } return false; } /** * 下载单个文件 * * @param remotePath:远程下载目录 * @param remoteFileName:下载文件名 * @param response * @return */ public boolean downFile(String remotePath, String newFileName, HttpServletResponse response) { OutputStream outputStream = null; boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } // 输出文件流 response.reset(); // 非常重要 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + new String(newFileName.getBytes("GBK"), "ISO-8859-1")); outputStream = response.getOutputStream(); sftp.get(homeDir + remotePath, outputStream); outputStream.flush(); outputStream.close(); if (logger.isInfoEnabled()) { logger.info("DownloadFile:" + newFileName + " success from sftp."); } return true; } catch (Exception e) { e.printStackTrace(); } finally { if (null != outputStream) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (_flag) disconnect(); } return false; } /** * 读取文件 * @param remoteFileName * @return */ public StringBuffer readFile(String remoteFileName) { StringBuffer resultBuffer = new StringBuffer(); InputStream in = null; boolean _flag = false; try { if (!isConnect()) { connect(); _flag = true; } in = sftp.get(homeDir + remoteFileName); if(in == null) return resultBuffer; BufferedReader br = new BufferedReader(new InputStreamReader(in, encoding)); String data = null; try { while ((data = br.readLine()) != null) { resultBuffer.append(data + "\n"); } } catch (IOException e) { logger.error("文件读取错误。"); e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); logger.debug("本地文件下载失败!", e); } finally { try { if (in != null) in.close(); } catch (Exception e) { // e.printStackTrace(); } if (_flag) disconnect(); } return resultBuffer; } /** * 写入字符串到FTP文件 * @param path * @param content */ public void writeToFtp(String path, String content) throws CustomException,Exception{ boolean _flag = false; try { if (!isConnect()) { connect(); _flag = true; } String remoteFileName = path.substring(path.lastIndexOf("/") + 1); String remotePath = path.substring(0, path.lastIndexOf("/") + 1); InputStream in = new ByteArrayInputStream(content.getBytes(encoding)); uploadFile(in, remoteFileName, remotePath); } catch (Exception e) { e.printStackTrace(); logger.debug("文件写入失败!", e); throw new CustomException(path + "写入失败!"); } finally { if (_flag) disconnect(); } } /** * 上传单个文件 * * @param remotePath:远程保存目录 * @param remoteFileName:保存文件名 * @param localPath:本地上传目录(以路径符号结束) * @param localFileName:上传的文件名 * @return */ public boolean uploadFile(InputStream in, String remoteFileName, String remotePath) { boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } createDir(remotePath); sftp.put(in, remoteFileName); return true; } catch (SftpException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (_flag) disconnect(); } return false; } /** * 批量上传文件 * * @param remotePath:远程保存目录 * @param localPath:本地上传目录(以路径符号结束) * @param del:上传后是否删除本地文件 * @return */ public boolean bacthUploadFile(String remotePath, String localPath, boolean del) { boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } File file = new File(localPath); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile() && files[i].getName().indexOf("bak") == -1) { if (this.uploadFile(new FileInputStream(files[i]), files[i].getName(), remotePath) && del) { deleteFile(localPath + files[i].getName()); } } } if (logger.isInfoEnabled()) { logger.info("upload file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is " + files.length); } return true; } catch (Exception e) { e.printStackTrace(); } finally { if (_flag) this.disconnect(); } return false; } /** * 删除本地文件 * * @param filePath * @return */ public boolean deleteFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return false; } if (!file.isFile()) { return false; } boolean rs = file.delete(); if (rs && logger.isInfoEnabled()) { logger.info("delete file success from local."); } return rs; } /** * 创建目录 * * @param createpath * @return */ public boolean createDir(String createpath) { boolean _flag = false; createpath = homeDir + createpath; try { if (!isConnect()){ connect(); _flag = true; } if (isDirExist(createpath)) { this.sftp.cd(createpath); return true; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if (isDirExist(filePath.toString())) { sftp.cd(filePath.toString()); } else { // 建立目录 sftp.mkdir(filePath.toString()); // 进入并设置为当前目录 sftp.cd(filePath.toString()); } } this.sftp.cd(createpath); return true; } catch (SftpException e) { e.printStackTrace(); } finally { if (_flag) disconnect(); } return false; } /** * 判断目录是否存在 * * @param directory * @return */ public boolean isDirExist(String directory) { boolean isDirExistFlag = false; boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } SftpATTRS sftpATTRS = sftp.lstat(directory); isDirExistFlag = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isDirExistFlag = false; } } finally { if (_flag) disconnect(); } return isDirExistFlag; } /** * 删除stfp文件 * * @param directory:要删除文件所在目录 * @param deleteFile:要删除的文件 * @param sftp */ public void deleteSFTP(String directory, String deleteFile) { boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } sftp.rm(homeDir + directory + deleteFile); if (logger.isInfoEnabled()) { logger.info("delete file success from sftp."); } } catch (Exception e) { e.printStackTrace(); } finally { if (_flag) disconnect(); } } /** * 如果目录不存在就创建目录 * * @param path */ public void mkdirs(String path) { File f = new File(path); String fs = f.getParent(); f = new File(fs); if (!f.exists()) { f.mkdirs(); } } /** * 列出目录下的文件 * * @param directory:要列出的目录 * @param sftp * @return * @throws SftpException */ public Vector listFiles(String directory) throws SftpException { boolean _flag = false; if (!isConnect()){ connect(); _flag = true; } Vector ls = sftp.ls(homeDir + directory); if (_flag) disconnect(); return ls; } public boolean isConnect() { return (this.sftp != null && this.sftp.isConnected() && this.sshSession != null && this.sshSession.isConnected()); } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public ChannelSftp getSftp() { return sftp; } public void setSftp(ChannelSftp sftp) { this.sftp = sftp; } }
ftpconfig.properties
#FTP配置文件 #============Attachment============# ATTACHMENT_username=sftp_hrdms ATTACHMENT_password=sftp_hrdms2019 ATTACHMENT_host=192.168.1.203 ATTACHMENT_port=22 ATTATEST_username=root ATTATEST_password=123123123 ATTATEST_host=120.79.79.189 ATTATEST_port=22
-
-
2019-10-09 15:26:43 qq_40807739 阅读数 125
-
-
【直通华为HCNA/HCNP系列S篇2】VRP系统使用、维护与...
全面介绍华为VRP系统的使用、维护与管理方法。主要包括(1)VRP系统的基本操作,(2)VRP软件系统组成与启动文件管理,(3)VRP系统软件和配置文件的备份、恢复方法配置与实验,(4)VRP系统登录:包括Console/MiniUSB口/Telnet/STelnet/HTTP和HTTPS登录方法配置与实验,(5)VRP文件系统管理:包括FTP/SFTP/SCP和FTPS设备访问方法配置与实验等。
48课时 886分钟 27944人学习 王达免费试看
最近需要从sftp上下载文件。我看到网上大部分都不支持多线程下载很多都会卡死,或者是排队下载。我也从网上copy了一份代码,看了一下。发现了原因。
- 卡死原因
因为很多都是一个session对应一个channel,但是没有做并发处理,导致有的session未被关闭。会话一直存在,它可以被垃圾回收,但是要等到下次gc时才会关闭该session。 - 排队下载
这就是对上面进行了并发处理,让其同步创建session,然后session创建channel,并且同步关闭channel和session。这样也就下载完成了。但是他们是同步下载,所以需要排队。 - 一个session个channel
如果是一个session多个channel,那么当所有channel下载完成关闭时,如果当前session没被关闭,那么所有的数据将停留在内存中,有时候你会发现,你结束掉java进程的时候,它所有数据都被flush到文件了。也就是关闭session。
我拿着改进了一下,将其每个下载对应一个session和一个channel。那么意味着每个session->channel是独立存在的,不存在冲突问题。下面是代码,可以参考下:
import com.jcraft.jsch.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import java.io.*; import java.util.Properties; /** * @author xoxo * @description sftp支持多线程下载 */ @Slf4j @Data public class SftpClient { private static String host = "192.168.10.130"; private static String username = "foo"; private static String password = "pass"; protected static String privateKey;// 密钥文件路径 protected static String passphrase;// 密钥口令 private static int port = 2222; @Data @AllArgsConstructor private static class SftpObject{ private Session session; private ChannelSftp channelSftp; } public static SftpObject connect() { JSch jsch = new JSch(); ChannelSftp sftp = null; Channel channel = null; Session session = null; try { if (!StringUtils.isEmpty(privateKey)) { // 使用密钥验证方式,密钥可以使有口令的密钥,也可以是没有口令的密钥 if (!StringUtils.isEmpty(passphrase)) { jsch.addIdentity(privateKey, passphrase); } else { jsch.addIdentity(privateKey); } } session = jsch.getSession(username, host, port); if (!StringUtils.isEmpty(password)) { session.setPassword(password); } Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no");// do not verify host // key session.setConfig(sshConfig); // session.setTimeout(timeout); // session.setServerAliveInterval(92000); session.connect(); // 参数sftp指明要打开的连接是sftp连接 channel = session.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; } catch (JSchException e) { log.error("连接【" + host + ":" + port + "】异常", e); } return new SftpObject(session,sftp); } /** * 关闭资源 */ public static void disconnect(SftpObject sftpObject) { if(sftpObject==null){ return; } ChannelSftp channelSftp = sftpObject.getChannelSftp(); Session session = sftpObject.getSession(); if (channelSftp != null) { if (channelSftp.isConnected()) { channelSftp.disconnect(); } } if (session != null) { if (session.isConnected()) { session.disconnect(); } } } /** * 下载单个文件 * * @param remoteFileName * 下载文件名 * @param localPath * 本地保存目录(以路径符号结束) * @param localFileName * 保存文件名 * @return */ public static boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) { log.info(remotePath + "/" + remoteFileName + "/" + localPath + "/" + localFileName); SftpObject sftpObject = null; try { sftpObject = connect(); ChannelSftp channelSftp = sftpObject.getChannelSftp(); channelSftp.cd(remotePath); File file = new File(localPath + localFileName); mkdirs(localPath + localFileName); channelSftp.get(remoteFileName, new FileOutputStream(file)); return true; } catch (FileNotFoundException e) { log.error("不存在文件,Path:" + remotePath + ",file:" + remoteFileName, e); } catch (SftpException e) { log.error("下载文件处理异常,Path:" + remotePath + ",file:" + remoteFileName, e); } finally { disconnect(sftpObject); } return false; } /** * 如果目录不存在就创建目录 * * @param path */ private static void mkdirs(String path) { File f = new File(path); String fs = f.getParent(); f = new File(fs); if (!f.exists()) { f.mkdirs(); } } public static void main(String[] args){ new Thread(()->{ downloadFile("/upload","java.pdf","D:/work/","xoxo1.pdf"); }).start(); new Thread(()->{ downloadFile("/upload","java.pdf","D:/work/","xoxo2.pdf"); }).start(); new Thread(()->{ downloadFile("/upload","java.pdf","D:/work/","xoxo3.pdf"); }).start(); } }
-
-
2017-09-01 12:02:25 qq_22074635 阅读数 4007
-
-
【直通华为HCNA/HCNP系列S篇2】VRP系统使用、维护与...
全面介绍华为VRP系统的使用、维护与管理方法。主要包括(1)VRP系统的基本操作,(2)VRP软件系统组成与启动文件管理,(3)VRP系统软件和配置文件的备份、恢复方法配置与实验,(4)VRP系统登录:包括Console/MiniUSB口/Telnet/STelnet/HTTP和HTTPS登录方法配置与实验,(5)VRP文件系统管理:包括FTP/SFTP/SCP和FTPS设备访问方法配置与实验等。
48课时 886分钟 27944人学习 王达免费试看
maven坐标
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.53</version> </dependency>
代码
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Vector; import org.apache.commons.lang.StringUtils; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class SftpUtil { /** * 连接sftp服务器 * * @param host * 主机 * @param port * 端口 * @param username * 用户名 * @param password * 密码 * @return */ public static ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); Session sshSession = jsch.getSession(username, host, port); System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; System.out.println("Connected to " + host + "."); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return sftp; } /** * 上传文件 * * @param directory * 上传的目录 * @param uploadFile * 要上传的文件 * @param sftp */ public static void upload(String directory, String uploadFile, ChannelSftp sftp) { /* * sftp.cd(directory); sftp.cd(dest); sftp.mkdir(dest); File file = new * File(uploadFile); sftp.put(new FileInputStream(file), * file.getName()); */ mkDir(directory, sftp); InputStream in = null; try { sftp.cd(directory); File file = new File(uploadFile); in = new FileInputStream(file); sftp.put(new FileInputStream(file), file.getName()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 下载文件 * * @param directory * 下载目录 * @param downloadFile * 下载的文件 * @param sftp */ public static InputStream download(String directory, String downloadFile, ChannelSftp sftp) { InputStream in = null; try { sftp.cd(directory); in = sftp.get(downloadFile); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return in; } /** * 删除文件 * * @param directory * 要删除文件所在目录 * @param deleteFile * 要删除的文件 * @param sftp */ public static void delete(String directory, String deleteFile, ChannelSftp sftp) { try { sftp.cd(directory); sftp.rm(deleteFile); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 列出目录下的文件 * * @param directory 要列出的目录 * @param sftp * @return * @throws SftpException */ public static Vector listFiles(String directory, ChannelSftp sftp) throws SftpException { return sftp.ls(directory); } /** * 获取目录name * * @param Vector 目录集合 * @return * @throws SftpException */ public static List<String> buildFiles(Vector ls) throws Exception { if (ls != null && ls.size() >= 0) { List<String> list = new ArrayList<String>(); for (int i = 0; i < ls.size(); i++) { LsEntry f = (LsEntry) ls.get(i); String nm = f.getFilename(); if (nm.equals(".") || nm.equals("..")) continue; list.add(nm); } return list; } return null; } /** * 打开指定目录 * * @param directory * directory * @return 是否打开目录 */ public static boolean openDir(String directory, ChannelSftp sftp) { try { sftp.cd(directory); return true; } catch (SftpException e) { return false; } } /** * 创建指定文件夹 * * @param dirName * dirName */ public static void mkDir(String dirName, ChannelSftp sftp) { String[] dirs = dirName.split("/"); try { String now = sftp.pwd(); sftp.cd("/"); for (int i = 0; i < dirs.length; i++) { if (StringUtils.isNotEmpty(dirs[i])) { boolean dirExists = openDir(dirs[i], sftp); if (!dirExists) { sftp.mkdir(dirs[i]); sftp.cd(dirs[i]); } } } sftp.cd(now); } catch (SftpException e) { e.printStackTrace(); } } }
-
-
2013-04-28 14:43:14 xinyoulinglei 阅读数 0
-
-
【直通华为HCNA/HCNP系列S篇2】VRP系统使用、维护与...
全面介绍华为VRP系统的使用、维护与管理方法。主要包括(1)VRP系统的基本操作,(2)VRP软件系统组成与启动文件管理,(3)VRP系统软件和配置文件的备份、恢复方法配置与实验,(4)VRP系统登录:包括Console/MiniUSB口/Telnet/STelnet/HTTP和HTTPS登录方法配置与实验,(5)VRP文件系统管理:包括FTP/SFTP/SCP和FTPS设备访问方法配置与实验等。
48课时 886分钟 27944人学习 王达免费试看
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;import org.apache.commons.lang.ArrayUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SFTPTool
{
/**
* 调测日志记录器。
*/
private static final DebugLog DEBUGGER = LogFactory.getDebugLog(SFTPTool.class);/**
* 运行日志记录器。
*/
private static final IcityRuntimeLog RUNTIMELOGGER = IcityLogFactory.getRuntimeLog(SFTPTool.class);/**
* Sftp客户端对象
*/
private ChannelSftp sftp = null;/**
* SFTP IP地址
*/
private String ip;/**
* SFTP 端口
*/
private String port;/**
* SFTP 用户名
*/
private String userName;/**
* SFTP 密码
*/
private String password;/**
* SFTP上传模式:BINARY
*/
// private static final int BINARY_FILE_TYPE = 2;/**
*
* 获取实例
*
* @return SFTPTool newinstance实例
*
*/
public static SFTPTool getNewInstance()
{
return new SFTPTool();
}/**
* 初始化连接参数
*
* @param sftpIP
* IP
* @param sftpPort
* 端口
* @param sftpUsername
* 用户名
* @param sftpPassword
* 密码
*/
public void init(String sftpIP, String sftpPort, String sftpUsername, String sftpPassword)
{
// 获取SFTP连接信息
this.ip = sftpIP;
this.port = sftpPort;
this.userName = sftpUsername;
this.password = sftpPassword;
}/**
* 从SFTP将符合约定命名的文件都下载到本地 .
*
* @param sftpDir
* SFTP服务器文件存放路径
* @param locDir
* 本地文件存放路径
* @param regex
* 指定文件名的 式
* @param needBackup
* 是否需要文件备份(true:是;false:否)
* @param needFullMatch
* 是否要求全局匹配(true:是;false:否)
* @param deleteFtpFile
* the delete ftp file
* @return 下载到本地的文件列表
*/
public List<File> synSFTPFileToLocal(String sftpDir, String locDir, String regex, boolean needBackup,
boolean needFullMatch, boolean deleteFtpFile)
{
List<File> files = new ArrayList<File>(KeyConstant.INITIAL_NUMBER);
try
{
this.connect(ip, Integer.parseInt(this.port), userName, password);// 获得FTP上文件名称列表
List<String> ftpFileNameList = this.listFiles(sftpDir, regex, needFullMatch);File localFile = null;
int size = ftpFileNameList.size();
// 根据每个FTP文件名称创建本地文件。
for (int i = 0; i < size; i++)
{
// 下载源文件
localFile = this.download(sftpDir, locDir, ftpFileNameList.get(i), deleteFtpFile);
if (localFile.exists())
{
files.add(localFile);
}
if (needBackup)
{
// 备份源文件生成默认备份文件路径(据请求文件路径,生成同级目录的备份文件夹绝对路径)
String parentDir = sftpDir.substring(NumberConstant.INT_0, sftpDir.lastIndexOf("/") + 1);
String backupDir = parentDir + TimetaskConstants.DEFAULT_BACKUP_DIRNAME;
boolean bakExists = openDir(backupDir);
if (bakExists)
{
this.uploadFile(backupDir, localFile);
}
else
{
boolean parentExists = openDir(parentDir);
if (parentExists)
{
sftp.mkdir(TimetaskConstants.DEFAULT_BACKUP_DIRNAME);
this.uploadFile(backupDir, localFile);
}
else
{
DEBUGGER.error("sftp parentDir no exisits ");
}
}
}
}
}
catch (Exception e)
{
DEBUGGER.error("synSFTPFileToLocal Exception", e);
}
finally
{
this.disconnect();
}
return files;
}/**
* 上传文件: <br>
*
* @param remotingPath
* 远程路径
* @param file
* 本地文件
* @param sftp
* sftp
* @return 是否上传成功
* @see
*/
public static boolean uploadFiles(String remotingPath, File file, ChannelSftp sftp)
{
boolean flag = false;
InputStream in = null;
try
{
if (!openDirs(sftp, remotingPath))
{
sftp.mkdir(remotingPath);
}
sftp.cd(remotingPath);
in = new FileInputStream(file);
sftp.put(in, file.getName());
if (file.exists())
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception e)
{
DEBUGGER.error("uploadFile Exception : " + e);
return false;
}
finally
{
if (null != in)
{
try
{
in.close();
}
catch (IOException e)
{
DEBUGGER.error("IOException : " + e);
}
}
}return flag;
}/**
* 打开指定目录
*
* @param sftp
* ChannelSftp
* @param directory
* directory
* @return 是否打开目录
*/
public static boolean openDirs(ChannelSftp sftp, String directory)
{
try
{
sftp.cd(directory);
return true;
}
catch (SftpException e)
{
DEBUGGER.error("openDir Exception : " + e);
return false;
}
}/**
* 连接sftp服务器
*
* @param sftpip
* ip地址
* @param sftpport
* 端口
* @param sftpusername
* 用户名
* @param sftppassword
* 密码
* @return channelSftp
* @throws SPMException
*/
public ChannelSftp connect(String sftpip, int sftpport, String sftpusername, String sftppassword)
{
sftp = new ChannelSftp();
try
{
JSch jsch = new JSch();
jsch.getSession(sftpusername, sftpip, sftpport);
Session sshSession = jsch.getSession(sftpusername, sftpip, sftpport);
RUNTIMELOGGER.info("Session created");
sshSession.setPassword(sftppassword);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
// 设置超时时间为
sshSession.setTimeout(Integer.parseInt(StaticInitData.getFtpConnectTimeOut()) * NumberConstant.INT_1000);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;// 设置文件类型
// ftpClient.setFileType(BINARY_FILE_TYPE);// 与防火墙相关
// ftpClient.enterLocalPassiveMode();
}
catch (JSchException e)
{
DEBUGGER.error("JSchException : {}", e);
}
return sftp;
}// /**
// * 创建指定文件夹
// *
// * @param dirName
// * dirName
// */
// public void mkDir(String dirName)
// {
// try
// {
// sftp.mkdir(dirName);
// }
// catch (SftpException e)
// {
// DEBUGGER.error("mkDir Exception : " + e);
// }
// }/**
* 创建指定文件夹
*
* @param dirName
* dirName
*/
public void mkDir(String dirName)
{
String[] dirs = dirName.split("/");
try
{
String now = sftp.pwd();
for (int i = 0; i < dirs.length; i++)
{
boolean dirExists = openDir(dirs[i]);
if (!dirExists)
{
sftp.mkdir(dirs[i]);
sftp.cd(dirs[i]);}
}
sftp.cd(now);
}
catch (SftpException e)
{
DEBUGGER.error("mkDir Exception : " + e);
}
}/**
* 打开指定目录
*
* @param directory
* directory
* @return 是否打开目录
*/
public boolean openDir(String directory)
{
try
{
if (!StringTools.isNullOrNone(directory))
{
sftp.cd(directory);
}
return true;
}
catch (SftpException e)
{
DEBUGGER.error("openDir Exception : " + e);
return false;
}
}/**
*
* 用sftp上传申请文档 测试报告 logo图片
*
* @param directory
* resourcePackage
* @param singleTableModel
* 单例模式
* @return flag
*/
public boolean uploadLogoFile(String directory, SingleTableModel singleTableModel)
{
File file = singleTableModel.getFileUpload();
boolean flag = false;
FileInputStream in = null;
try
{
String now = sftp.pwd();
// sftp.cd(directory);
// add by lizhonghu 创建目录
openAndMakeDir(directory);
in = new FileInputStream(file);
sftp.put(in, singleTableModel.getFileUploadFileName());
sftp.cd(now);
if (file.exists())
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception e)
{
DEBUGGER.error("uploadFile Exception : " + e);
}
finally
{
try
{
if (null != in)
{
try
{
in.close();
}
catch (IOException e)
{
DEBUGGER.error("IOException : " + e);
}
}
}
catch (Exception e)
{
DEBUGGER.error("Exception : " + e);
}
}
return flag;
}/**
* 创建指定文件夹
*
* @param directory
* 路径+文件夹名
* @return 成功与否
*/
public boolean openAndMakeDir(String directory)
{
try
{
String now = sftp.pwd();
if (now.equals(directory))
{
return true;
}
else
{
try
{
if (!StringTools.isNullOrNone(directory))
{
sftp.cd(directory);
}
return true;
}
catch (SftpException e)
{
if (directory.startsWith(now))
{
directory = directory.replaceFirst(now, "");
}
String[] dirList = directory.split("/");
dirList = (String[]) ArrayUtils.removeElement(dirList, "");
for (String dir : dirList)
{
try
{
sftp.cd(dir);
}
catch (SftpException e1)
{
sftp.mkdir(dir);
sftp.cd(dir);
}
}
return true;
}
}
}
catch (SftpException e)
{
DEBUGGER.error("openDir Exception : " + directory, e);
return false;
}
}/**
* 上传文件
*
* @param directory
* 上传的目录
* @param file
* 要上传的文件 parentDir 上传目录的上级目录
* @return 是否上传
*/
public boolean uploadFile(String directory, File file)
{
boolean flag = false;
FileInputStream in = null;
try
{
String now = sftp.pwd();
if (!StringTools.isNullOrNone(directory))
{
sftp.cd(directory);
}
in = new FileInputStream(file);
sftp.put(in, file.getName());
sftp.cd(now);
if (file.exists())
{
flag = true;
}
else
{
flag = false;
}
}
catch (Exception e)
{
DEBUGGER.error("uploadFile Exception : " + e);
}
finally
{
try
{
if (null != in)
{
try
{
in.close();
}
catch (IOException e)
{
DEBUGGER.error("IOException : " + e);
}
}
}
catch (Exception e)
{
DEBUGGER.error("Exception : " + e);
}
}
return flag;
}/**
* 下载文件.
*
* @param ftpDir
* 存放下载文件的SFTP路径
* @param locDir
* 下载的文件 SFTP上的文件名称
* @param ftpFileName
* FTP上的文件名称
* @param deleteFtpFile
* the delete ftp file
* @return 本地文件对象
* @throws FileNotFoundException
* FileNotFoundException
*/
public File download(String ftpDir, String locDir, String ftpFileName, boolean deleteFtpFile)
throws FileNotFoundException
{
File file = null;
FileOutputStream output = null;
String localDir = CommonTools.buildLocalDir(locDir).append(File.separator).append(ftpFileName).toString();
try
{
String now = sftp.pwd();
if (!StringTools.isNullOrNone(ftpDir))
{
sftp.cd(ftpDir);
}
file = new File(localDir);
output = new FileOutputStream(file);
sftp.get(ftpFileName, output);
sftp.cd(now);
if (deleteFtpFile)
{
sftp.rm(ftpFileName);
}
}
catch (SftpException e)
{
if (DEBUGGER.isErrorEnable())
{
DEBUGGER.error("Failed to download", e);
}
e.toString();
}
finally
{
if (null != output)
{
try
{
output.close();
}
catch (IOException e)
{
DEBUGGER.error("create localFile failed:" + e);
}
}
}
return file;
}/**
* Description:断开FTP连接 <br>
*/
public void disconnect()
{
if (null != sftp)
{
sftp.disconnect();if (null != sftp.getSession())
{
sftp.getSession().disconnect();
}
}
}/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile)
{
try
{
String now = sftp.pwd();
if (!StringTools.isNullOrNone(directory))
{
sftp.cd(directory);
}
sftp.rm(deleteFile);
sftp.cd(now);
}
catch (Exception e)
{
e.printStackTrace();
}
}/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @param regex
* 指定文件名的 式
* @param needFullMatch
* 是否要求全局匹配(true:是;false:否)
* @return 文件列表
* @throws SftpException
* SftpException
* @throws SPMException
* SPMException
*/
@SuppressWarnings("unchecked")
public List<String> listFiles(String directory, String regex, boolean needFullMatch) throws SftpException,
SPMException
{
List<String> ftpFileNameList = new ArrayList<String>(KeyConstant.INITIAL_NUMBER);
Vector<LsEntry> sftpFile = sftp.ls(directory);
LsEntry isEntity = null;
String fileName = null;
Iterator<LsEntry> sftpFileNames = sftpFile.iterator();
while (sftpFileNames.hasNext())
{
isEntity = (LsEntry) sftpFileNames.next();
fileName = isEntity.getFilename();if (StringTools.isNullOrNone(regex))
{
ftpFileNameList.add(fileName);
}
else
{
if (fileName.matches(regex))
{
ftpFileNameList.add(fileName);
}
else
{
if (needFullMatch)
{
throw new SPMException("SYSTEM ERROR",
"system error,all file check terminated,invalid file name " + fileName);
}
else
{
DEBUGGER.error("Invalid file named " + fileName);
}
}
}
}return ftpFileNameList;
} -


java sftp工具类 相关内容

java sftp工具类 相关内容

java sftp工具类 相关内容

java sftp工具类 相关内容
-
阅读数 0
-
SFTP上传、下载(递归下载)、删除(递归删除)之Java工具类
阅读数 580
-
阅读数 0
-
阅读数 3565
-
阅读数 0