Java的ssh传输文件

需要下载几个jar包,下载链接:https://mvnrepository.com/
原文如下:

maven依赖


 
 
  1. <!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
  2. <dependency>
  3. <groupId>com.jcraft </groupId>
  4. <artifactId>jsch </artifactId>
  5. <version>0.1.54 </version>
  6. </dependency>

代码如下


 
 
  1. package com;
  2. import java.io.BufferedInputStream;
  3. import java.io.File;
  4. import java.io.FileFilter;
  5. import java.io.FileInputStream;
  6. import java.io.InputStream;
  7. import java.util.ArrayList;
  8. import java.util.Date;
  9. import java.util.List;
  10. import org.apache.commons.logging.Log;
  11. import org.apache.commons.logging.LogFactory;
  12. import com.jcraft.jsch.ChannelSftp;
  13. import com.jcraft.jsch.JSch;
  14. import com.jcraft.jsch.Session;
  15. public class Ftp {
  16. //打印log日志
  17. private static final Log logger = LogFactory.getLog(Ftp.class);
  18. private static Date last_push_date = null;
  19. private Session sshSession;
  20. private ChannelSftp channel;
  21. private static ThreadLocal<Ftp> sftpLocal = new ThreadLocal<Ftp>();
  22. private Ftp(String host, int port, String username, String password) throws Exception {
  23. JSch jsch = new JSch();
  24. jsch.getSession(username, host, port);
  25. //根据用户名,密码,端口号获取session
  26. sshSession = jsch.getSession(username, host, port);
  27. sshSession.setPassword(password);
  28. //修改服务器/etc/ssh/sshd_config 中 GSSAPIAuthentication的值yes为no,解决用户不能远程登录
  29. sshSession.setConfig( "userauth.gssapi-with-mic", "no");
  30. //为session对象设置properties,第一次访问服务器时不用输入yes
  31. sshSession.setConfig( "StrictHostKeyChecking", "no");
  32. sshSession.connect();
  33. //获取sftp通道
  34. channel = (ChannelSftp)sshSession.openChannel( "sftp");
  35. channel.connect();
  36. logger.info( "连接ftp成功!");
  37. }
  38. /**
  39. * 是否已连接
  40. *
  41. * @return
  42. */
  43. private boolean isConnected() {
  44. return null != channel && channel.isConnected();
  45. }
  46. /**
  47. * 获取本地线程存储的sftp客户端
  48. *
  49. * @return
  50. * @throws Exception
  51. */
  52. public static Ftp getSftpUtil(String host, int port, String username, String password) throws Exception {
  53. //获取本地线程
  54. Ftp sftpUtil = sftpLocal.get();
  55. if ( null == sftpUtil || !sftpUtil.isConnected()) {
  56. //将新连接防止本地线程,实现并发处理
  57. sftpLocal.set( new Ftp(host, port, username, password));
  58. }
  59. return sftpLocal.get();
  60. }
  61. /**
  62. * 释放本地线程存储的sftp客户端
  63. */
  64. public static void release() {
  65. if ( null != sftpLocal.get()) {
  66. sftpLocal.get().closeChannel();
  67. logger.info( "关闭连接" + sftpLocal.get().sshSession);
  68. sftpLocal.set( null);
  69. }
  70. }
  71. /**
  72. * 关闭通道
  73. *
  74. * @throws Exception
  75. */
  76. public void closeChannel() {
  77. if ( null != channel) {
  78. try {
  79. channel.disconnect();
  80. } catch (Exception e) {
  81. logger.error( "关闭SFTP通道发生异常:", e);
  82. }
  83. }
  84. if ( null != sshSession) {
  85. try {
  86. sshSession.disconnect();
  87. } catch (Exception e) {
  88. logger.error( "SFTP关闭 session异常:", e);
  89. }
  90. }
  91. }
  92. /**
  93. * @param directory 上传ftp的目录
  94. * @param uploadFile 本地文件目录
  95. * @param isDel 是否删除原文件
  96. *
  97. */
  98. public void upload(String directory, String uploadFile, boolean isDel) throws Exception {
  99. try { //执行列表展示ls 命令
  100. channel.ls(directory); //执行盘符切换cd 命令
  101. channel.cd(directory);
  102. List<File> files = getFiles(uploadFile, new ArrayList<File>());
  103. for ( int i = 0; i < files.size(); i++) {
  104. File file = files.get(i);
  105. InputStream input = new BufferedInputStream( new FileInputStream(file));
  106. channel.put(input, file.getName());
  107. try {
  108. if (input != null) input.close();
  109. } catch (Exception e) {
  110. e.printStackTrace();
  111. logger.error(file.getName() + "关闭文件时.....异常!" + e.getMessage());
  112. }
  113. if (file.exists()&&isDel) {
  114. boolean b = file.delete();
  115. logger.info(file.getName() + "文件上传完毕!删除标识:" + b);
  116. }
  117. }
  118. } catch (Exception e) {
  119. logger.error( "【子目录创建中】:",e);
  120. //创建子目录
  121. channel.mkdir(directory);
  122. }
  123. }
  124. //获取文件
  125. public List<File> getFiles(String realpath, List<File> files) {
  126. File realFile = new File(realpath);
  127. if (realFile.isDirectory()) {
  128. File[] subfiles = realFile.listFiles( new FileFilter() {
  129. @Override
  130. public boolean accept(File file) {
  131. if ( null == last_push_date ) {
  132. return true;
  133. } else {
  134. long modifyDate = file.lastModified();
  135. return modifyDate > last_push_date.getTime();
  136. }
  137. }
  138. });
  139. for (File file : subfiles) {
  140. if (file.isDirectory()) {
  141. getFiles(file.getAbsolutePath(), files);
  142. } else {
  143. files.add(file);
  144. }
  145. if ( null == last_push_date) {
  146. last_push_date = new Date(file.lastModified());
  147. } else {
  148. long modifyDate = file.lastModified();
  149. if (modifyDate > last_push_date.getTime()) {
  150. last_push_date = new Date(modifyDate);
  151. }
  152. }
  153. }
  154. } else {
  155. files.add(realFile);
  156. }
  157. return files;
  158. }
  159. public static void main(String[] args) throws Exception {
  160. Ftp ftp = new Ftp( "100.100.100.100", 22, "root", "root");
  161. ftp.upload( "/home/haha/push", "D:\\abc.jar", false);
  162. ftp.closeChannel();
  163. }
  164. }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值