java sftp上传文件

java sftp 免密码上传文件到目标服务器(密钥文件登陆)

添加maven依赖

可以去 https://mvnrepository.com 选择使用的版本

<dependency>
   <groupId>com.jcraft</groupId>
   <artifactId>jsch</artifactId>
   <version>0.1.55</version>
</dependency>

代码部分

需要注意的是有两种方式去连接远程服务器,一是利用需要的密码来登录,二是生成私钥文件登录

package cn.com.dsa.gac.flashconfig.util;

import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class SFTPUtils {

    private static Session session = null;
    private static ChannelSftp channel = null;

    private static final Logger logger = LoggerFactory.getLogger(SFTPUtils.class);

    public static ChannelSftp getConnect(String loginName,String passWord, String ipAddr, int port, String privatekeyFile) {
        JSch jsch = new JSch();
        try {
            logger.info("sftp [ ftpHost = " + ipAddr + "  ftpPort = " + port + "  ftpUserName = " + loginName + " ]");
            session = jsch.getSession(loginName, ipAddr, port);
            logger.info("Session created.");
            //这里私钥文件的位置默认是在项目resource/privatekey目录下的private_key文件
            InputStream privateKeyStream = SFTPUtils.class.getClassLoader().getResourceAsStream("privatekey/private_key");
            //如果默认位置没有私钥文件,那么选择传入的私钥文件路径privatekeyFile
            if (StringUtils.isNotBlank(privatekeyFile)) {
                File keyFile = new File(privatekeyFile);
                if (keyFile.exists()) {
                    try {
                        privateKeyStream = new FileInputStream(keyFile);
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                        throw new RuntimeException(e);
                    }
                }
            }
            if (privateKeyStream != null) {
                byte[] privateKeyBytes = privateKeyStream.readAllBytes();
                jsch.addIdentity("id_rsa", privateKeyBytes, null, null);
                privateKeyStream.close();
            }
            //如若选择私钥登录,那么不需要输入代码,如果密码登录,则可以去掉privateKeyStream相关代码
            //session.setPassword(passWord);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            logger.info("Session connected . Opening SFTP Channel.");
			//指定打开的连接是sftp连接
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
            logger.info("Connected successfully to ftpHost = " + ipAddr + ",as ftpUserName = " + loginName + ", returning: " + channel);
        } catch (JSchException e) {
            logger.error("sftp getConnect error : " + e);
            throw new RuntimeException(e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
        return channel;
    }

    /**
    *  完成传输文件后需要关闭channel
    */
    public static void closeChannel() throws Exception {
        try {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        } catch (Exception e) {
            throw new Exception("close ftp error.");
        }
    }

    /**
     *  上传文件方法
     */
    public static void uploadFolder(String localFolderPath, String remoteFolderPath) throws SftpException {
        File localFolder = new File(localFolderPath);

        if (localFolder.isFile()) {
            channel.put(localFolder.getAbsolutePath(), remoteFolderPath);
            return;
        }
        try {
            File[] files = localFolder.listFiles();
            if (files != null) {
                for (File file : files) {
                    createRemoteDirectory(remoteFolderPath);
                    String newRemoteFolder = remoteFolderPath + "/" + file.getName();
                    FileInputStream fis = new FileInputStream(file);
                    try {
                        channel.put(fis, newRemoteFolder);
                    } finally {
                        fis.close();
                    }
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public static void createRemoteDirectory(String remoteDirectory) throws SftpException {
        try {
            SftpATTRS attrs = channel.stat(remoteDirectory);
            if (attrs == null) {
                createRemoteDirectory(new File(remoteDirectory).getParent());
                channel.mkdir(remoteDirectory);
            }
        } catch (SftpException e) {
            channel.mkdir(remoteDirectory);
        }
    }

    public static void main(String[] args) {
        try {
            //开启连接
            SFTPUtils.getConnect(
                "root",
                "123456",
                "192.168.1.1",
                22,
                "privatekey/private_Key"
            );
            //创建服务器上的文件夹
            String remoteFilePath = "/data";
            SFTPUtils.createRemoteDirectory(remoteFilePath);

            //需要上传的文件路径
            String localFilePath = "bin\\tmp\\test";
            SFTPUtils.uploadFolder(localFilePath, remoteFilePath);

            //关闭连接
            SFTPUtils.closeChannel();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值