ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java实现从ftp服务器拷贝文件到另一台服务器

2021-11-18 23:02:31  阅读:313  来源: 互联网

标签:ftp shell 另一台 new sftp client error 服务器 String


目录


前言

通过ftp连接ftp服务器,通过sftp连接另外一台服务器,实现文件拷贝。


1、连接ftp

/**
     * 连接FTP
     */
    public void connect(String host, int port, String user, String pwd) {
        FTPClient client = new FTPClient();
        try {
            // 连接
            client.connect(host, port);
            // 登陆
            if (user == null || "".equals(user)) {
                client.login("anonymous", "anonymous");
            } else {
                client.login(user, pwd);
            }
            // 二进制文件支持
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 获取FTP应答
            int reply = client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                client.disconnect();
                return;
            }
            FTPClientConfig config = new FTPClientConfig(client.getSystemType().split(" ")[0]);
            client.configure(config);
            client.setBufferSize(1024);
            client.enterLocalPassiveMode();
            client.setControlEncoding("utf-8");
            this.client = client;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2、连接sftp

/**
     * 连接sftp服务器
     *
     * @param host     主机
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     */
    public void sessionConnect(String host, int port, String username, String password) {
        try {
            this.jsch = new JSch();
            this.sshSession = jsch.getSession(username, host, port);
            this.sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            this.sshSession.setConfig(sshConfig);
            this.sshSession.connect();
        } catch (Exception e) {
            log.error("SftpUtil Session host=[" + host + "];port=[" + port + "];user=[" + username
                    + "];passwd=[" + password + "] error : ", e);
        }
    }


    /**
     * 连接sftp
     */
    public SftpUtils sftpConnect() {
        if (sftp == null) {
            try {
                Channel channelSftp = this.sshSession.openChannel("sftp");
                this.sftp = (ChannelSftp) channelSftp;
                sftp.connect();
            } catch (Exception e) {
                log.error("SftpUtil ChannelSftp error : ", e.getMessage());
            }
        }
        return this;
    }

3、获取ftp文件流

 /**
     * 获取远程文件的输出流
     *
     * @param client     ftp连接,这里传进来是因为不能在该方法的最后释放连接
     * @param fileName   文件名称,FTP上的文件名称
     * @param remotePath ftp上的远程目录文件
     */
    public static InputStream retrieveFileStream(FTPClient client, String fileName, String remotePath) throws Exception {
        boolean success = false;

        try {
            success = switchDirectory(client, remotePath, false);
            if (success) {
                return client.retrieveFileStream(fileName);
            }
        } catch (Exception e) {
            log.debug("获取ftp文件流异常,error: {}", e.getMessage());
            throw new RuntimeException("获取ftp文件流异常 error" + e.getMessage());
        }
        return null;
    }

4、在sftp连接服务器上创建目录

		String mkdir = "mkdir -p " + remotePath;
        String exit = "exit";
        sftp.shellConnect().executeShell(mkdir, exit);
 /**
     * 创建shell连接
     */
    public SftpUtil shellConnect() {
        if (shell == null) {
            try {
                Channel chnanelShell = this.sshSession.openChannel("shell");
                shell = (ChannelShell) chnanelShell;
                shell.connect();
            } catch (Exception e) {
                log.error("SftpUtil ChannelShell error : ", e.getMessage());
            }
        }
        return this;
    }
/**
     * 执行shell 命令
     */
    public boolean executeShell(String... cmds) {
        ChannelShell shell = null;
        try {
            Channel chnanelShell = this.sshSession.openChannel("shell");
            shell = (ChannelShell) chnanelShell;
            shell.connect();
        } catch (JSchException e) {
            log.error("SftpUtil ChannelShell error : ", e);
        }
        try {
            InputStream in = shell.getInputStream();
            OutputStream out = shell.getOutputStream();
            PrintWriter writer = new PrintWriter(out);
            for (String cmd : cmds) {
                writer.println(cmd);
            }
            writer.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String msg = "";
            StringBuilder result = new StringBuilder();
            while ((msg = reader.readLine()) != null) {
//                result.append(msg).append(System.lineSeparator());
            }
        } catch (IOException e) {
            throw new RuntimeException("执行命令出错,cmd : " + ArrayUtils.toString(cmds) + " , error : " + e.getMessage());
        } finally {
            shell.disconnect();
        }

        return true;
    }

5、上传到sftp所在服务器

  /**
     * 上传文件
     *
     * @param src      要上传的文件流
     * @param dir      上传的目录
     * @param fileName 文件名称
     */
    public boolean uploadStream(InputStream src, String dir, String fileName) throws Exception {
        boolean success = false;
        try {
            this.sftp.cd(dir);
            this.sftp.put(src, fileName);
            success = true;
        } catch (Exception e) {
            log.error("SftpUtil upload directory=[" + dir + "];uploadFile=[" + fileName + "] error : ", e.getMessage());
            throw new RuntimeException("上传文件异常," + "upload directory=[" + dir + "];uploadFile=[" + fileName + "] error:" + e.getMessage());
        } finally {
            try {
                if (src != null) {
                    src.close();
                }
            } catch (IOException e) {
                log.error("SftpUtil upload directory=[" + dir + "];uploadFile=[" + fileName + "] close FileInputStream error : ", e);
            }
        }
        return success;
    }

标签:ftp,shell,另一台,new,sftp,client,error,服务器,String
来源: https://blog.csdn.net/RenshenLi/article/details/121411863

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有