在日常开发中,遇见远程下载的需求,具体是在windows环境连接linux环境进行远程下载文件。下面是选用jsch组件进行的实现。
JSch(Java Secure Channel)是一个ssh2的java实现,允许连接到一个ssh服务器(即典型的xshell连接方式),并且可以使用端口转发,文件传输等。使用SFTP协议。
SFTP(Secure File Transfer Protocol)安全文件传送协议,可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式,但是传输效率比普通的FTP要低。

public class SftpUtils {private static final Logger log = LoggerFactory.getLogger(SftpUtils.class);private String host;private String username;private String password;private int port = 22;private int timeOut = 6000;private ChannelSftp channelSftp = null;private Session sshSession = null;public SftpUtils(String host, String username, String password) {this.host = host;this.username = username;this.password = password;}/*** 通过SFTP连接服务器*/public void connect() {try {JSch jsch = new JSch();sshSession = jsch.getSession(username, host, port);sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.setTimeout(timeOut);sshSession.connect();channelSftp = (ChannelSftp) sshSession.openChannel("sftp");channelSftp.connect();} catch (Exception e) {log.error(e.getMessage());e.printStackTrace();}}/*** 关闭连接*/public void disconnect() {if (this.channelSftp != null) {if (this.channelSftp.isConnected()) {this.channelSftp.disconnect();}}if (this.sshSession != null) {if (this.sshSession.isConnected()) {this.sshSession.disconnect();}}}/*** 批量下载文件* @param remotePath:远程下载目录* @param localPath:本地保存目录* @return*/public List<String> batchDownLoadFile(String remotePath, String localPath) {return batchDownLoadFile(remotePath, localPath, null, null, false);}/*** 批量下载文件* @param remotePath:远程下载目录* @param localPath:本地保存目录* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)* @param fileEndFormat:下载文件格式(文件格式,为空不做检验)* @param del:下载后是否删除sftp文件* @return*/public List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) {List<String> filenames = new ArrayList<>();try {Vector<?> vector = listFiles(remotePath);if (vector.size() > 0) {//size()中包含(. 和 ..)所以实际文件数目=size-2log.info("本次处理文件个数不为零,开始下载...fileSize={}", vector.size()-2);Iterator<?> it = vector.iterator();while (it.hasNext()) {ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();String filename = entry.getFilename();SftpATTRS attrs = entry.getAttrs();if(".".equals(filename) || "..".equals(filename)) {continue;}if (!attrs.isDir()) {boolean flag;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 = downloadFile(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 = downloadFile(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 = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}} else {flag = downloadFile(remotePath, filename, localPath, filename);if (flag) {filenames.add(localFileName);if (flag && del) {deleteSFTP(remotePath, filename);}}}}else {String newRemotePath = remotePath+ filename+ "/";String newLocalPath = localPath+ filename+ "\\";File fi = new File(newLocalPath);if(!fi.exists()) {fi.mkdirs();}batchDownLoadFile(newRemotePath, newLocalPath);}}}} catch (SftpException e) {log.error(e.getMessage());e.printStackTrace();} finally {}return filenames;}/*** 下载单个文件* @param remotePath:远程下载目录* @param remoteFileName:下载文件名* @param localPath:本地保存目录* @param localFileName:保存文件名* @return*/public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {FileOutputStream fileOutput = null;try {File file = new File(localPath + localFileName);File path = new File(localPath);if(!path.exists()) {path.mkdirs();}fileOutput = new FileOutputStream(file);channelSftp.get(remotePath + remoteFileName, fileOutput);System.out.println(remotePath + remoteFileName + "下载完成");return true;} catch (FileNotFoundException e) {log.error(e.getMessage());e.printStackTrace();} catch (SftpException e) {log.error(e.getMessage());e.printStackTrace();} finally {if (null != fileOutput) {try {fileOutput.close();} catch (IOException e) {log.error(e.getMessage());e.printStackTrace();}}}return false;}/*** 上传单个文件* @param remotePath:远程保存目录* @param remoteFileName:保存文件名* @param localPath:本地上传目录(以路径符号结束)* @param localFileName:上传的文件名* @return*/public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {FileInputStream in = null;try {createDir(remotePath);File file = new File(localPath + localFileName);in = new FileInputStream(file);channelSftp.put(in, remoteFileName);return true;} catch (FileNotFoundException e) {log.error(e.getMessage());e.printStackTrace();} catch (SftpException e) {log.error(e.getMessage());e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {log.error(e.getMessage());e.printStackTrace();}}}return false;}/*** 批量上传文件* @param remotePath:远程保存目录* @param localPath:本地上传目录(以路径符号结束)* @param del:上传后是否删除本地文件* @return*/public boolean batchUploadFile(String remotePath, String localPath, boolean del) {try {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(remotePath, files[i].getName(), localPath, files[i].getName()) && del) {deleteFile(localPath + files[i].getName());}}}return true;} catch (Exception e) {log.error(e.getMessage());e.printStackTrace();} finally {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();return rs;}/*** 创建目录* @param createPath* @return*/public boolean createDir(String createPath) {try {if (isDirExist(createPath)) {this.channelSftp.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())) {channelSftp.cd(filePath.toString());} else {// 建立目录channelSftp.mkdir(filePath.toString());// 进入并设置为当前目录channelSftp.cd(filePath.toString());}}this.channelSftp.cd(createPath);return true;} catch (SftpException e) {log.error(e.getMessage());e.printStackTrace();}return false;}/*** 判断目录是否存在* @param directory* @return*/public boolean isDirExist(String directory) {boolean isDirExistFlag = false;try {SftpATTRS sftpATTRS = channelSftp.lstat(directory);isDirExistFlag = true;return sftpATTRS.isDir();} catch (Exception e) {log.error(e.getMessage());if (e.getMessage().toLowerCase().equals("no such file")) {isDirExistFlag = false;}}return isDirExistFlag;}/*** 删除stfp文件* @param directory:要删除文件所在目录* @param deleteFile:要删除的文件*/public void deleteSFTP(String directory, String deleteFile) {try {channelSftp.rm(directory + deleteFile);} catch (Exception e) {log.error(e.getMessage());e.printStackTrace();}}/*** 列出目录下的文件* @param directory:要列出的目录* @return* @throws SftpException*/public Vector<?> listFiles(String directory) throws SftpException {return channelSftp.ls(directory);}public static void main(String[] args) {SftpUtils sftpUtils = null;try {sftpUtils = new SftpUtils("192.168.1.1", "root", "root");sftpUtils.connect();sftpUtils.downloadFile("/opt/","1.pdf","D:\\","1.pdf");sftpUtils.batchDownLoadFile("/opt/", "D:\\11\\", "2021", null, false);} catch (Exception e) {log.error(e.getMessage());e.printStackTrace();} finally {sftpUtils.disconnect();}}}

Java之jsch远程下载相关推荐

  1. java使用Jsch实现远程操作linux服务器进行文件上传、下载,删除和显示目录信息...

    1.java使用Jsch实现远程操作linux服务器进行文件上传.下载,删除和显示目录信息. 参考链接:https://www.cnblogs.com/longyg/archive/2012/06/2 ...

  2. Java从SFTP服务器下载文件一

    最近对接一个需求,要用SFTP去服务器上取文件,这里记录下自己的思路. SFTP下载文件需要用到jsch的jar包,我用的是jsch-0.1.54.jar,可以到http://www.jcraft.c ...

  3. java分布式对象——远程方法中的参数和返回值+远程对象激活

    [0]README 1)本文文字描述转自 core java volume 2, 旨在学习 java分布式对象--远程方法中的参数和返回值+远程对象激活 的相关知识: [1]远程方法中的参数和返回值 ...

  4. centos 远程安装java程序_centos7远程服务器中redis的安装与java连接

    1.下载安装redis 在远程服务器中你想下载的位置执行以下命令来下载redis文件到服务器中 $ wget http://download.redis.io/releases/redis-4.0.9 ...

  5. java scp发送文件到服务器,Java实现往远程服务器传输文件

    Java实现往远程服务器传输文件 内容精选 换一换 已成功登录Java性能分析.待安装Guardian的服务器已开启sshd.待安装Guardian的服务器已安装JRE,JRE版本要求为Huawei ...

  6. jenkins部署 java项目到远程 windows服务器

    jenkins部署 java项目到远程 windows服务器 1.查看windows服务器是否有 ssh服务. cmd模式,输入 ssh.如果报错就去安装ssh(可以去下 openSSH) 2.然后直 ...

  7. java 高效文件批量下载_java实现高效文件下载

    java实现高效文件下载 本文我们介绍几种方法下载文件.从基本JAVA IO 到 NIO包,也介绍第三方库的一些方法,如Async Http Client 和 Apache Commons IO. 最 ...

  8. java学习一站式资料下载(项目源码及视频)

    Javaweb练手项目下载 1,电子商城项目  采用了Struts.spring.hibernate,数据库使用了MySQL. 2,CRM客户关系管理系统  没有使用框架,采用了jsp.Servlet ...

  9. 树莓派迅雷远程下载 | 树莓派小无相系列

    拥有一台24小时远程下载器是很惬意的一件事,可以在空闲时间下载一些影片或其他资料,比方在工作地点添加下载影片的任务,到家之后便可以观看,而无需为网络操心,此外也可以将一些大文件的下载挂载下载器上,无需 ...

最新文章

  1. redchat怎么编写shell脚本_shell脚本编写思路
  2. Codeforces D. Fair 多源BFS求最短路
  3. 智能家居——IoT零基础入门篇
  4. vue使用python_如何使用Python和Vue创建两人游戏
  5. 程序员生存定律--使人生永动的势能
  6. Kubernetes实战:高可用集群的搭建和部署
  7. Linux ssh 允许 root用户 登录
  8. python如何查询文件路径_Python使用os.listdir和os.walk获取文件路径
  9. 【转】彻底删除打印机
  10. python编译安装没有c扩展_python – 为什么我在安装simplejson时得到“C扩展无法编译”?...
  11. 去掉左边0_TiDB 4.0 在 VIPKID 的应用实践
  12. 量子计算机基本信息单位,量子计算机.ppt
  13. 使用phantomjs将网页转换成pdf或者长图片
  14. github博客绑定个性域名
  15. inkscape推荐插件安装
  16. 单件模式(Singleton Pattern
  17. ICPC2019徐州区域赛 H.Yuuki and a problem
  18. 大数据学长面试之boss直聘面试题
  19. 怎么理解预训练模型?
  20. 命令行把java项目打成jar包

热门文章

  1. HDU-7092 仓颉造数
  2. 惠普linux设置u盘启动不了,惠普电脑怎么设置u盘启动(hp笔记本u盘启动不了)...
  3. jupyter 常用命令
  4. 两数之和 Two Sum
  5. 《数据库应用系统实践》------ 小区停车管理系统
  6. C++ 程序猿面试题和答案
  7. 088 定积分几何应用之面积、体积、弧长计算方法总结
  8. 第三部分:填写志愿的思路
  9. 肘方法确定聚类数k_肘方法确定KMeans聚类的最佳K值
  10. macOS Monterey 12.6.8 (21G725) 正式版发布,ISO、IPSW、PKG 下载