java 通过SSH方式连接远程主机并上传和下载文件

  1. package com.app.pt.backup.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.InputStream;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.util.Iterator;  
  8. import java.util.Vector;  
  9.   
  10. import org.apache.commons.logging.Log;  
  11. import org.apache.commons.logging.LogFactory;  
  12.   
  13. import com.app.common.util.FileUtil;  
  14. import com.jcraft.jsch.ChannelSftp;  
  15. import com.jcraft.jsch.ChannelSftp.LsEntry;  
  16. import com.jcraft.jsch.JSch;  
  17. import com.jcraft.jsch.JSchException;  
  18. import com.jcraft.jsch.Session;  
  19. import com.jcraft.jsch.SftpException;  
  20.   
  21. /** 
  22.  * SFTP帮助类 
  23.  * @author wangbailin 
  24.  * 
  25.  */  
  26. public class SFTPUtil {  
  27.       
  28.     private static Log log = LogFactory.getLog(SFTPUtil.class);  
  29.       
  30.     /** 
  31.      * 连接sftp服务器 
  32.      * @param host 远程主机ip地址 
  33.      * @param port sftp连接端口,null 时为默认端口 
  34.      * @param user 用户名 
  35.      * @param password 密码 
  36.      * @return 
  37.      * @throws JSchException  
  38.      */  
  39.     public static Session connect(String host, Integer port, String user, String password) throws JSchException{  
  40.         Session session = null;  
  41.         try {  
  42.             JSch jsch = new JSch();  
  43.             if(port != null){  
  44.                 session = jsch.getSession(user, host, port.intValue());  
  45.             }else{  
  46.                 session = jsch.getSession(user, host);  
  47.             }  
  48.             session.setPassword(password);  
  49.             //设置第一次登陆的时候提示,可选值:(ask | yes | no)  
  50.             session.setConfig("StrictHostKeyChecking""no");  
  51.             //30秒连接超时  
  52.             session.connect(30000);  
  53.         } catch (JSchException e) {  
  54.             e.printStackTrace();  
  55.             System.out.println("SFTPUitl 获取连接发生错误");  
  56.             throw e;  
  57.         }  
  58.         return session;  
  59.     }  
  60.       
  61.     /** 
  62.      * sftp上传文件(夹) 
  63.      * @param directory 
  64.      * @param uploadFile 
  65.      * @param sftp 
  66.      * @throws Exception  
  67.      */  
  68.     public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{  
  69.         System.out.println("sftp upload file [directory] : "+directory);  
  70.         System.out.println("sftp upload file [uploadFile] : "+ uploadFile);  
  71.         File file = new File(uploadFile);  
  72.         if(file.exists()){  
  73.             //这里有点投机取巧,因为ChannelSftp无法去判读远程linux主机的文件路径,无奈之举  
  74.             try {  
  75.                 Vector content = sftp.ls(directory);  
  76.                 if(content == null){  
  77.                     sftp.mkdir(directory);  
  78.                 }  
  79.             } catch (SftpException e) {  
  80.                 sftp.mkdir(directory);  
  81.             }  
  82.             //进入目标路径  
  83.             sftp.cd(directory);  
  84.             if(file.isFile()){  
  85.                 InputStream ins = new FileInputStream(file);  
  86.                 //中文名称的  
  87.                 sftp.put(ins, new String(file.getName().getBytes(),"UTF-8"));  
  88.                 //sftp.setFilenameEncoding("UTF-8");  
  89.             }else{  
  90.                 File[] files = file.listFiles();  
  91.                 for (File file2 : files) {  
  92.                     String dir = file2.getAbsolutePath();  
  93.                     if(file2.isDirectory()){  
  94.                         String str = dir.substring(dir.lastIndexOf(file2.separator));  
  95.                         directory = FileUtil.normalize(directory + str);  
  96.                     }  
  97.                     upload(directory,dir,sftp);  
  98.                 }  
  99.             }  
  100.         }  
  101.     }  
  102.       
  103.     /** 
  104.      * sftp下载文件(夹) 
  105.      * @param directory 下载文件上级目录 
  106.      * @param srcFile 下载文件完全路径 
  107.      * @param saveFile 保存文件路径 
  108.      * @param sftp ChannelSftp 
  109.      * @throws UnsupportedEncodingException 
  110.      */  
  111.     public static void download(String directory,String srcFile, String saveFile, ChannelSftp sftp) throws UnsupportedEncodingException {  
  112.         Vector conts = null;  
  113.         try{  
  114.             conts = sftp.ls(srcFile);  
  115.         } catch (SftpException e) {  
  116.             e.printStackTrace();  
  117.             log.debug("ChannelSftp sftp罗列文件发生错误",e);  
  118.         }  
  119.         File file = new File(saveFile);  
  120.         if(!file.exists()) file.mkdir();  
  121.         //文件  
  122.         if(srcFile.indexOf(".") > -1){  
  123.             try {  
  124.                 sftp.get(srcFile, saveFile);  
  125.             } catch (SftpException e) {  
  126.                 e.printStackTrace();  
  127.                 log.debug("ChannelSftp sftp下载文件发生错误",e);  
  128.             }  
  129.         }else{  
  130.         //文件夹(路径)  
  131.             for (Iterator iterator = conts.iterator(); iterator.hasNext();) {  
  132.                 LsEntry obj =  (LsEntry) iterator.next();  
  133.                 String filename = new String(obj.getFilename().getBytes(),"UTF-8");  
  134.                 if(!(filename.indexOf(".") > -1)){  
  135.                     directory = FileUtil.normalize(directory + System.getProperty("file.separator") + filename);  
  136.                     srcFile = directory;  
  137.                     saveFile = FileUtil.normalize(saveFile + System.getProperty("file.separator") + filename);  
  138.                 }else{  
  139.                     //扫描到文件名为".."这样的直接跳过  
  140.                     String[] arrs = filename.split("\\.");  
  141.                     if((arrs.length > 0) && (arrs[0].length() > 0)){  
  142.                         srcFile = FileUtil.normalize(directory + System.getProperty("file.separator") + filename);  
  143.                     }else{  
  144.                         continue;  
  145.                     }  
  146.                 }  
  147.                 download(directory, srcFile, saveFile, sftp);  
  148.             }  
  149.         }  
  150.     }  
  151. }  
    使用sftp帮助类上传或下载:
[java]  view plain  copy
  1. ChannelSftp sftp = null;  
  2. Session session = null;  
  3. try {  
  4.     session = SFTPUtil.connect(host, port, username, password);  
  5.     Channel channel = session.openChannel("sftp");  
  6.     channel.connect();  
  7.     sftp = (ChannelSftp) channel;  
  8.     SFTPUtil.upload(destDir, srcfile.getAbsolutePath(), sftp);  
  9. catch (Exception e) {  
  10.     e.printStackTrace();  
  11.     logger.debug(e);  
  12.     return UtilMisc.toMap("flag","failure","msg","备份文件到远程主机发生错误");  
  13. }finally{  
  14.     if(sftp != null)sftp.disconnect();  
  15.     if(session != null)session.disconnect();  
  16. }  
  17. 原文出处:https://blog.csdn.net/wangbailin2009/article/details/20232999
  18. 所需要的一个jar包:https://download.csdn.net/download/star_admin/10456836
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值