Java之jsch远程下载

本文介绍如何利用JSch库在Windows环境中通过SSH连接Linux服务器,实现SFTP协议下的文件批量下载、上传功能,包括连接配置、通道操作和示例代码演示。

在日常开发中,遇见远程下载的需求,具体是在windows环境连接linux环境进行远程下载文件。下面是选用jsch组件进行的实现。
JSch(Java Secure Channel)是一个ssh2的java实现,允许连接到一个ssh服务器(即典型的xshell连接方式),并且可以使用端口转发,文件传输等。使用SFTP协议。
SFTP(Secure File Transfer Protocol)安全文件传送协议,可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式,但是传输效率比普通的FTP要低。

public class SftpUtils {

    private static final Logger log = LoggerFactory.getLogger(SftpUtils.class);

    private String host;
    private String username;
    private String password;
    private int port = 22;
    private int timeOut = 6000;
    private ChannelSftp channelSftp = null;
    private Session sshSession = null;

    public SftpUtils(String host, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
    }

    /**
     * 通过SFTP连接服务器
     */
    public void connect() {
        try {
            JSch jsch = new JSch();
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.setTimeout(timeOut);
            sshSession.connect();

            channelSftp = (ChannelSftp) sshSession.openChannel("sftp");
            channelSftp.connect();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        if (this.channelSftp != null) {
            if (this.channelSftp.isConnected()) {
                this.channelSftp.disconnect();
            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
            }
        }
    }

    /**
     * 批量下载文件
     * @param remotePath:远程下载目录
     * @param localPath:本地保存目录
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath) {
        return batchDownLoadFile(remotePath, localPath, null, null, false);
    }

    /**
     * 批量下载文件
     * @param remotePath:远程下载目录
     * @param localPath:本地保存目录
     * @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
     * @param fileEndFormat:下载文件格式(文件格式,为空不做检验)
     * @param del:下载后是否删除sftp文件
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) {
        List<String> filenames = new ArrayList<>();
        try {
     
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值