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

来源:互联网 发布:上海程序员工资多少 编辑:程序博客网 时间:2024/06/07 02:18
Java连接远程主机的方式有多种,这里和大家分享的是通过ssh方式连接远程主机,使用的是jsch这个jar包,资源在这里。

    不懂ssh为何物的朋友可以从网上找找相关资料,这里只简单的解释下:SSH 为 Secure Shell(安全外壳协议) 的缩写,由 IETF 的网络工作小组(Network Working Group)所制定,为建立在应用层和传输层基础上的安全协议。SSH在传输层提供服务器认证,数据机密性,信息完整性等的支持,并为服务器提供客户端的身份鉴别。利用SSH协议可以有效防止远程管理过程中的信息泄露问题。通过SSH可以对所有传输的数据进行加密,也能够防止DNS欺骗和IP欺骗。

    下面是自己写的一个sftp帮助类,代码中有错误或者是不合理完善的地方希望能够指出,共同学习成长:

Java代码  收藏代码
  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代码  收藏代码
  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();  

0 0
原创粉丝点击