JSch包实现SFTP上传、下载

JSch包maven仓库地址:

复制代码

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

复制代码

 sftp 上传下载工具类

复制代码

package wenjun.zhang.jsch;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;

/** 
 * sftp 上传下载工具类
 */
public class SftpUtil {

    private static Logger logger = LoggerFactory.getLogger(SftpUtil.class);
    
    /**
     * 获取Sftp对象
     * @param param
     * @return
     */
    public  static SftpConfig getSftpObj(String param) {
        SftpConfig sftpConfig = new SftpConfig();
        if (StringUtils.isNotBlank(param)) {
            JSONObject jsonObj = JSONObject.fromObject(param);
            sftpConfig = (SftpConfig) JSONObject.toBean(jsonObj, SftpConfig.class);
        }
        return sftpConfig;
    }

    /** sftp 上传*/
    public static boolean upload(SftpConfig config, String baseDir, String fileName, String filePath) {
        logger.info("路径:baseDir="+baseDir);
        SftpChannel sftpChannel = new SftpChannel();
        ChannelSftp sftp = null;
        try {
            if (StringUtils.isNotBlank(config.getPrivateKeyPath())) {
                sftp = sftpChannel.connectByIdentity(config);
            } else {
                sftp = sftpChannel.connectByPwd(config);
            }
            if (sftp.isConnected()) {
                logger.info("连接服务器成功");
            } else {
                logger.error("连接服务器失败");
                return false;
            }
            //检查路径
            if(!isExist(sftp, baseDir)){
                logger.error("创建sftp服务器路径失败:" + baseDir);
                return false;
            }
            String dst = baseDir + "/" + fileName;
            String src = filePath + "/" + fileName;
            logger.info("开始上传,本地服务器路径:["+src +"]目标服务器路径:["+dst+"]");
            sftp.put(src, dst);
            logger.info("上传成功");
            return true;
        } catch (Exception e) {
            logger.error("上传失败", e);
            return false;
        } finally {
            sftpChannel.closeChannel();
        }
    }

    /**sftp 下载 */
    public static boolean down(SftpConfig config, String baseDir, String fileName1, String filePath, String fileName2 ) {
        SftpChannel sftpChannel = new SftpChannel();
        ChannelSftp sftp = null;
        try {
            if (StringUtils.isNotBlank(config.getPrivateKeyPath())) {
                sftp = sftpChannel.connectByIdentity(config);
            } else {
                sftp = sftpChannel.connectByPwd(config);
            }
            if (sftp.isConnected()) {
                logger.info("连接服务器成功");
            } else {
                logger.error("连接服务器失败");
                return false;
            }
            String dst = "";
            if (StringUtils.isBlank(fileName2)) {
                dst = filePath + fileName1;
            } else{
                dst = filePath + fileName2;
            }
            String src = baseDir+ "/" + fileName1;
            logger.info("开始下载,sftp服务器路径:["+src +"]目标服务器路径:["+dst+"]");
            sftp.get(src, dst);
            logger.info("下载成功");
            return true;
        } catch (Exception e) {
            logger.error("下载失败", e);
            return false;
        } finally {
            sftpChannel.closeChannel();
        }
    }
    
    /**
     * 判断文件夹是否存在
     * true 目录创建成功,false 目录创建失败
      * @param sftp
     * @param filePath 文件夹路径
     * @return
     */
    public static boolean isExist(ChannelSftp sftp, String filePath) {
        String paths[] = filePath.split("\\/");
        String dir = paths[0];
        for (int i = 0; i < paths.length - 1; i++) {
            dir = dir + "/" + paths[i + 1];
            try{
                sftp.cd(dir);
            }catch(SftpException sException){
                if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){
                    try {
                        sftp.mkdir(dir);
                    } catch (SftpException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
        }
        return true;
    }
}

复制代码

SftpChannel  sftp连接

复制代码

package wenjun.zhang.jsch;

import java.util.Properties;

import org.apache.commons.lang.StringUtils;

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;

public class SftpChannel {
    Session session = null;
    Channel channel = null;

    //端口默认为22
    public static final int SFTP_DEFAULT_PORT = 22;

    /** 利用JSch包实现SFTP下载、上传文件(秘钥方式登陆)*/
    public ChannelSftp connectByIdentity(SftpConfig sftpConfig) throws JSchException {
        JSch jsch = new JSch();
        int port = SFTP_DEFAULT_PORT;
        //设置密钥和密码
        //支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了
        if (StringUtils.isNotBlank(sftpConfig.getPrivateKeyPath())) {
            if (StringUtils.isNotBlank(sftpConfig.getPassphrase())) {
                //设置带口令的密钥
                jsch.addIdentity(sftpConfig.getPrivateKeyPath(), sftpConfig.getPassphrase());
            } else {
                //设置不带口令的密钥
                jsch.addIdentity(sftpConfig.getPrivateKeyPath());
            }
        }
        if (sftpConfig.getPort() != null) {
            port = Integer.valueOf(sftpConfig.getPort());
        }
        if (port > 0) {
            //采用指定的端口连接服务器
            session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp(), port);
        } else {
            //连接服务器,采用默认端口
            session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp());
        }
        if (session == null) {
            throw new JSchException("session为空,连接失败");
        }
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        session.setConfig(sshConfig);
        session.setTimeout(30000);
        session.connect();
        //创建sftp通信通道
        channel = (Channel) session.openChannel("sftp");
        channel.connect();
        return (ChannelSftp) channel;
    }

    /** 利用JSch包实现SFTP下载、上传文件(用户名密码方式登陆) */
    public ChannelSftp connectByPwd(SftpConfig sftpConfig) throws JSchException {
        JSch jsch = new JSch();
        int port = SFTP_DEFAULT_PORT;
        if (sftpConfig.getPort() != null) {
            port = Integer.valueOf(sftpConfig.getPort());
        }
        if (port > 0) {
            //采用指定的端口连接服务器
            session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp(), port);
        } else {
            //连接服务器,采用默认端口
            session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp());
        }
        if (session == null) {
            throw new JSchException("session为空,连接失败");
        }
        //设置登陆主机的密码
        session.setPassword(sftpConfig.getPwd());//设置密码
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        session.setConfig(sshConfig);
        session.setTimeout(30000);
        session.connect();
        //创建sftp通信通道
        channel = (Channel) session.openChannel("sftp");
        channel.connect();
        return (ChannelSftp) channel;
    }

    public void closeChannel() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }

}

复制代码

sftp配置类

复制代码

package wenjun.zhang.jsch;

/**
 * sftp 配置
 */
public class SftpConfig {
    /** 密钥地址 */
    private String privateKeyPath;
    /** 口令 */
    private String passphrase;
    
    private String ip;
    
    private Integer port;
    
    private String username;
    
    private String pwd;
    
    private String path;
    
    private String baseDir;
    
    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getBaseDir() {
        return baseDir;
    }

    public void setBaseDir(String baseDir) {
        this.baseDir = baseDir;
    }

    public String getPrivateKeyPath() {
        return privateKeyPath;
    }

    public void setPrivateKeyPath(String privateKeyPath) {
        this.privateKeyPath = privateKeyPath;
    }

    public String getPassphrase() {
        return passphrase;
    }

    public void setPassphrase(String passphrase) {
        this.passphrase = passphrase;
    }

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSch是一个Java库,用于在Java程序中连接和操作SFTP服务器。通过JSch,你可以使用SFTP协议在本地和远程服务器之间传输文件。下面是一个使用JSch连接SFTP服务器的示例代码: ```java JSch jsch = new JSch(); Session session = jsch.getSession("username", "hostname", port); session.setPassword("password"); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; // 在这里可以执行SFTP操作,比如上传下载、删除文件等 channel.disconnect(); session.disconnect(); ``` 以上代码中,你需要替换`username`、`hostname`、`port`和`password`为你实际的SFTP服务器的用户名、主机名、端口和密码。通过调用`session.connect()`方法建立与服务器的连接,然后通过`session.openChannel("sftp")`打开SFTP通道,最后通过`channel.connect()`连接到SFTP服务器。你可以在这个连接上执行各种SFTP操作,比如上传下载、删除文件等。最后,通过`channel.disconnect()`和`session.disconnect()`关闭连接。 如果你想读取服务器上指定路径下的所有文件,可以使用以下代码: ```java Vector<ChannelSftp.LsEntry> files = sftp.ls("/path/to/directory"); for (ChannelSftp.LsEntry file : files) { String filename = file.getFilename(); boolean isDirectory = file.getAttrs().isDir(); System.out.println(filename + " is a directory: " + isDirectory); } ``` 以上代码中,你需要将`/path/to/directory`替换为你想要读取的目录路径。通过调用`sftp.ls()`方法可以获取指定路径下的所有文件和文件夹的信息,然后通过遍历`files`列表可以获取每个文件的名称和是否是文件夹。 请注意,使用JSch连接SFTP服务器需要添加相应的依赖。你可以在你的项目的`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.53</version> </dependency> ``` 这样,你就可以使用JSch库连接SFTP服务器并执行相应的操作了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值