对sftp服务器的上传下载

    //上传
    public int push() {
        try {
            File file = new File("d:\\test");
            File[] files = file.listFiles();
            for (File f : files) {
                String ip = "服务器ip";
                String address = "服务器地址";
                String username = "用户名";
                String userpass = "密码";
                pushFileBySftp(ip, 22, username, userpass, address);
            }
        } catch (Exception e) {
            logger.info("连接失败", e);
            return -1;
        }
        return 0;
    }

  //下载
  public int pull() {
        try {
        String path = "wenjian"; //在sftp上存放的文件夹
            String ip = "服务器ip";
            String address = "服务器地址" + "/" + path;  //确保路径真实存在
                String username = "用户名";
                String userpass = "密码";

            //1.连接sftp
            ChannelSftp sftp = connectSFTP(ip, 22, username, userpass);
            if (sftp == null) {
                logger.info("推送失败");
                return -1;
            }

			//展示出目录下所有文件
            Vector files = sftp.ls(address);
            int size = files.size() - 2;
            if (size > 0) {
                logger.info("本次处理文件个数不为零,开始下载...fileSize=" + size);
                Iterator it = files.iterator();
                while (it.hasNext()) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                    String filename = entry.getFilename();
                    if (filename.equals("..") || filename.equals("."))
                        continue;
                    downloadFile(address, filename);
                }
                logger.info(">>>>>>>>FtpUtil-->downloadFile--ftp下载文件结束>>>>>>>>>>>>>");
            }
            //断开连接
            disconnect();
        } catch (Exception e) {
            logger.info("下载失败", e);
            return -1;
        }
        return 0;
    }


//推送文件
    public int pushFileBySftp(String host, int port, String username, String password, String address) {
        try {
            //1.连接sftp
            ChannelSftp sftp = connectSFTP(host, port, username, password);
            if (sftp == null) {
                logger.info("推送失败");
                return -1;
            }

            //2.推送文件开始
            File file = new File("d:\\test");
            String path = "wenjian"; //在sftp上存放的文件夹
            File[] files = file.listFiles();
            for (File f : files) {
                    boolean flag = pushFileBySftp(address + "/" + path, file  + File.separator + f.getName());    //File.separator == "/"
                    if (!flag) {
                        logger.info("推送失败");
                        return -1;
                    }
            }
            //关闭连接
            disconnect();
        } catch (Exception e) {
            logger.error("SFTP推送文件异常:" + e);
            return -1;
        }
        return 0;
    }

 /**
     * 连接sftp服务器
     *
     * @return ChannelSftp sftp类型
     * @throws
     */
    public ChannelSftp connectSFTP(String host, int port, String username, String password) throws JSchException {
        logger.info("sftp连接开始>>>>>>host=" + host + ">>>port" + port + ">>>username=" + username);
        JSch jsch = new JSch();
        try {
            sshSession = jsch.getSession(username, host, port);//
            sshSession.setPassword(password);               // 设置密码
            Properties properties = new Properties();
            properties.put("StrictHostKeyChecking", "no");
            properties.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
            sshSession.setConfig(properties);               // 为Session对象设置propertie
            sshSession.connect();
            logger.info("ftp---Session connected.");
            Channel channel = sshSession.openChannel("sftp"); // 打开SFTP通道
            channel.connect();
            logger.info("Opening Channel.");
            sftp = (ChannelSftp) channel;
            logger.info("ftp---Connected to " + host);
        } catch (JSchException e) {
            logger.error("SFtp推送文件 connect异常", e);
            return null;
        }
        return sftp;
    }


/**
     * sftp推送文件
     *
     * @param directory  上传的目录
     * @param uploadFile 要上传的文件
     */
    public boolean pushFileBySftp(String directory, String uploadFile) throws Exception {
        logger.info("sftp推送文件" + uploadFile + "开始>>>>>>>>>>>>>");
        try {
            try {
                sftp.cd(directory);
            } catch (SftpException e) {
                sftp.mkdir(directory);
                File file = new File(directory);
                file.setExecutable(true);//设置可执行权限
                file.setWritable(true);//设置可写权限
                file.setReadable(true);//设置可读权限
                sftp.cd(directory);
            }
            File file = new File(uploadFile);
            if (file == null || !file.exists() || file.isDirectory()) {
                logger.error("待上传的文件不存在:" + uploadFile);
                return false;
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            sftp.put(fileInputStream, file.getName());
            fileInputStream.close();
            logger.info("sftp推送文件结束>>>>>>>>>>>>>");
            return true;
        } catch (Exception e) {
            logger.error("sftp推送文件异常:", e);
            return false;
        }
    }

    /**
     * 断开sftp连接
     */
    public void disconnect() throws Exception {
        try {
            if (this.sftp != null) {
                if (this.sftp.isConnected()) {
                    this.sftp.disconnect();
                } else if (this.sftp.isClosed()) {
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("关闭sftp连接失败");
        }
        try {
            if (this.sftp.getSession() != null) {
                if (this.sftp.getSession().isConnected()) {
                    this.sftp.getSession().disconnect();
                }
            }
        } catch (JSchException e) {
            logger.error(e.getMessage(), e);
        }
    }


    public static void main(String[] args) {
      	//上传
        push();
        //下载
        pull();
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值