sftp上传 - 待完

Posted frank_quan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sftp上传 - 待完相关的知识,希望对你有一定的参考价值。

1、搭建本地sftp

  1.1、下载msftpsrvr.exe软件

      下载地址:http://www.download3k.com/Install-Core-FTP-Mini-SFTP-Server.html

      

 

  1.2、双击msftpsrvr.exe,录入sftp信息

    

 

2、工具类

SftpUploadUtil

package com.hundsun.channel.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;

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.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class SftpUploadUtil {
    
    public static final Log logger = LogFactory.getLog(SftpUploadUtil.class);
    
    /**
     * 连接sftp服务器
     * @param host 主机
     * @param port 端口
     * @param username 用户名
     * @param password 密码
     * @param privateKey 密钥文件路径
     * @param passphrase 密钥口令
     * @return
     */
    public ChannelSftp connect(String host, int port, String username,String password,String privateKey,String passphrase) {
     ChannelSftp sftp = null;
     try {
      JSch jsch = new JSch();
      jsch.getSession(username, host, port);
      if (privateKey != null && !"".equals(privateKey)) {
          //使用密钥验证方式,密钥可以使有口令的密钥,也可以是没有口令的密钥
          if (passphrase != null && !"".equals(passphrase)) {
              jsch.addIdentity(privateKey, passphrase);
          } else {
              jsch.addIdentity(privateKey);
          }
      }      
      
      Session sshSession = jsch.getSession(username, host, port);
      System.out.println("Session created.");
      if (password != null && !"".equals(password)) {
          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 + ".");
      //System.out.println("登录成功");
     } catch (Exception e) {
         System.out.println("------");
         e.printStackTrace();
     }
     return sftp;
    }

    /**
     * 关闭
     * @param sftp
     * @param sshSession
     * @throws JSchException 
     */
    public void close(ChannelSftp sftp) throws JSchException {
        if (null!=sftp) {
            if (null!=sftp.getSession()) {
                sftp.getSession().disconnect();
            }   
            sftp.disconnect();
        }

    }

    
    
    
    /**
     * 上传文件
     * @param directory 上传的目录
     * @param uploadFile 要上传的文件
     * @param sftp
     */
    public void upload(String directory, String uploadFile, ChannelSftp sftp) {
     try {
      sftp.cd(directory);
      File file=new File(uploadFile);
      sftp.put(new FileInputStream(file), file.getName());
      System.out.println("上传成功!");
     } 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 {
            logger.info("下载目录:" + directory + ",下载文件:" + downloadFile + ",存本地路径:" + saveFile);
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     * @param directory 要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {
     try {
      sftp.cd(directory);
      sftp.rm(deleteFile);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
 
    /**
     * 列出目录下的文件
     * @param directory 要列出的目录
     * @param sftp
     * @return
     * @throws SftpException
     */
    public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException{
     return sftp.ls(directory);
    }
    
    /**
     * 创建文件夹
     * @param sftp
     * @param directory
     * @throws SftpException 
     */
    public void createFolder(ChannelSftp  sftp,String directory) throws SftpException {
              
        sftp.mkdir(directory);
    }   
    
     
    public static void main(String[] args) {
        
        /*
        Vector<LsEntry> vector = new Vector<LsEntry>();
        String host="192.168.54.112";
        int port=22;
        String username="wjs";
        String password="wjs@567";
        //上传的目录
        String directory="/home/wjs/upload/1001/"+DateUtil.getDateTime("yyyyMMdd", new Date());
        System.out.println("directory:--------------"+directory);
        
        //要上传的文件
        String uploadFile="F:\\\\upload\\\\1001\\\\20151102\\\\info_1001_9000_20151102.txt";

        SftpUploadUtil sf = new SftpUploadUtil(); 
        
        //获取连接   
        ChannelSftp  sftp = sf.connect(host, port, username, password); 
      
        //创建文件夹
        try {
            //home/wjs/upload/1001
            vector = sftp.ls(directory);
        } catch (SftpException e) {
            // TODO Auto-generated catch block
            if (e.id == 2 || "No such file".equals(e.getMessage())) {
                Iterator<LsEntry> it = vector.iterator();
                while (it.hasNext()) {
                    LsEntry lsEntry = it.next();
                    System.out.println(lsEntry.getLongname());
                    System.out.println(lsEntry.getLongname().startsWith("d"));
                }
                try {
                    sftp.mkdir(directory);
                    //上传文件   
                    sf.upload(directory, uploadFile, sftp);
                    File file = new File(uploadFile);
                    long fileSize = file.length();

                    sftp.put(directory + "/info_1001_9000_20151026.txt", new FileProgressMonitor(
                        fileSize), ChannelSftp.OVERWRITE);
                    sftp.quit();
                    sf.close(sftp);
                } catch (SftpException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (JSchException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
            }
        } 
    */}
}
View Code

 

3、测试连接

    public static void main(String[] args) throws Exception {
        SftpUploadUtil sfUtil = new SftpUploadUtil();
        String sftpHost = "10.23.10.39";
        int sftpPort = 22; // 端口表字段暂时未定义
        String sftpUserName = "quanbs";
        String password = "123456";
        String privateKey = ""; // 秘钥文件路径
        String passphrase = ""; // 秘钥口令
        ChannelSftp sftp = sfUtil.connect(sftpHost, sftpPort, sftpUserName, password, privateKey, passphrase);
    }

运行结果(连接成功):

 

4、测试sftp上传

    public static void main(String[] args) throws Exception {
        SftpUploadUtil sfUtil = new SftpUploadUtil();
        String sftpHost = "10.23.10.39";
        int sftpPort = 22; // 端口表字段暂时未定义
        String sftpUserName = "quanbs";
        String password = "123456";
        String privateKey = ""; // 秘钥文件路径
        String passphrase = ""; // 秘钥口令
        ChannelSftp sftp = sfUtil.connect(sftpHost, sftpPort, sftpUserName, password, privateKey, passphrase);
        
        // 测试sftp上传
        testUploadFile(sfUtil, sftp);
    }

 

    /**
     * 测试上传文件
     * @param sfUtil
     * @param sftp
     * @throws SftpException
     */
    public static void testUploadFile(SftpUploadUtil sfUtil, ChannelSftp sftp) throws SftpException{
        String sftpDirectory = "E:"+File.separator+"sftp";
        sftpDirectory = "\\\\";
        String uploadFile = "D:\\\\log.zip";
        List lsList = getLsListName(File.separator, sftp); // 获取目录下的文件名List
        String date = DateUtils.convertDateToLong(new Date(), "yyyyMMdd").toString(); // 当天文件夹 20161026
        if (!lsList.contains(date)) // 当天日期文件夹不存在则创建
            sftp.mkdir(date);
        
        sftpDirectory += date;
        
        sfUtil.upload(sftpDirectory, uploadFile, sftp);
        
    }
    /**
     * 获取目录下的文件名List
     * @param path 目录
     * @param sftp
     * @throws SftpException
     */
    private static List<String> getLsListName(String path, ChannelSftp sftp) throws SftpException{
        List<String> list = new ArrayList<String>();
        Vector vector = sftp.ls(File.separator);
        Iterator<LsEntry> it = vector.iterator();
        while (it.hasNext()) {
            LsEntry lsEntry = it.next();
            list.add(lsEntry.getFilename());
        }
        return list;
    } 

运行结果:

 

 附:

DateUtils

package com.hundsun.channel.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {

    public static SimpleDateFormat FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");

    public static SimpleDateFormat FORMAT_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static SimpleDateFormat FORMAT_DATE_SIMPLE = new SimpleDateFormat("yyyyMMdd");

    public static SimpleDateFormat FORMAT_DATETIME_SIMPLE = new SimpleDateFormat("yyyyMMddHHmmss");

    public static SimpleDateFormat FORMAT_DATE_CN = new SimpleDateFormat("yyyy��MM��dd��");

    public static SimpleDateFormat FORMAT_DATETIME_CN = new SimpleDateFormat("yyyy��MM��dd��HHʱmm��ss��");

    public static SimpleDateFormat FORMAT_DATETIME_HOUR = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public static Date getDateTime(String dateStr, SimpleDateFormat format) {
        Date date = null;
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
        return date;
    }

    public static String getDateTimeStr(Date date, SimpleDateFormat format) {
        if (date == null || format == null) {
            return null;
        }
        return format.format(date);
    }

    public static Date getDate(String dateStr) {
        if (dateStr == null || "".equals(dateStr)) {
            return null;
        }
        return getDateTime(dateStr, FORMAT_DATE);
    }

    public static Date getDateTime(String dateStr) {
        return getDateTime(dateStr, FORMAT_DATETIME);
    }

    public static String getDateStr(Date date) {
        return getDateTimeStr(date, FORMAT_DATE);
    }

    public static String getDateTimeStr(Date date) {
        return getDateTimeStr(date, FORMAT_DATETIME);
    }

    public static long getDiffDays(Date startTime, Date endTime) {
        long quot = 0;
        if (startTime == null || endTime == null) {
            return quot;
        }
        SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd");
        try {
            Date endDate = ft.parse(ft.format(endTime));
            Date startDate = ft.parse(ft.format(startTime));
            quot = endDate.getTime() - startDate.getTime();
            quot = quot / 1000 / 60 / 60 / 24;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return quot;
    }

    public static Long convertDateToLong(Date date, String format) {
        SimpleDateFormat ft = new SimpleDateFormat(format);
        String formatStr = ft.format(date);
        long parseLong = Long.parseLong(formatStr);
        return parseLong;
    }

    public static Long convertDateToLong(Date date) {
        String formatStr = FORMAT_DATETIME_SIMPLE.format(date);
        long parseLong = Long.parseLong(formatStr);
        return parseLong;
    }
}
View Code

 

 

待完,很粗糙的东西 ,花了10分钟整理了下,要赶最后一班地铁回家了。 又是漫长的1个半小时。。。。 

以上是关于sftp上传 - 待完的主要内容,如果未能解决你的问题,请参考以下文章

仅20行代码,实现文件自动化上传至sftp

使用 SFTP 上传文件

Java利用JSch实现sftp通过ssh上传下载删除文件及配置代码

java通过sftp上传文件

我的代码库-Java8实现FTP与SFTP文件上传下载

sftp java 上传