java之Jsch实现Linux的文件上传与下载

本文介绍如何使用JSch库实现SFTP功能,包括连接SSH服务器、端口转发、X11转发、文件传输等。详细展示了SFTP的访问及实现方式,包括依赖包配置、代码示例和常见API如put、get、cd、ls等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、JSch是Java Secure Channel的缩写。JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。

  本文只介绍如何使用JSch实现的SFTP功能。

  SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式。SFTP是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。

  二、需要的依赖包pom.xml

        <dependency>
            <groupId>jsch</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.8</version>
        </dependency>

  三、sftp的访问,以及实现方式

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.*;
import java.util.Properties;

public class SftpFile {
    private static String cimepath = PropertiesUtil.getProperties("mapping.properties").getProperty("cimepath");
    public static void main(String[] args) throws Exception {

        //声明JSCH对象
        JSch jSch = new JSch();
        //获取一个Linux会话
        Session session = jSch.getSession("root", "10.0.40.98", 22);
        //设置登录密码
        session.setPassword("密码");
        //关闭key的检验
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        session.setConfig(sshConfig);
        //连接Linux
        session.connect();
        //通过sftp的方式连接
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();       
        //TODO 判断目录是否存在,不存在创建
        SftpUtil.createDir(cimepath,channel);
        //上传文件
        File file = new File("d:\\1.txt");
        InputStream inputStream = new FileInputStream(file);
        channel.put(inputStream, "/root/file/2.txt");
        //下载文件
        OutputStream out = new FileOutputStream("d:\\4.txt");
        channel.get("/root/file/1.txt", out);
        //关闭流
        inputStream.close();
        out.close();
    }
}
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

/**
 * @Auther: feifei
 * @Date: 2019/8/15 10:54
 * @Description:
 */
public class SftpUtil {

    /**
     * @Description:判断目录是否存在
     * @author: feifei
     * @Date: 2019/8/15 11:04
     * @Param: directory
     * @Param: sftp
     * @Return: boolean
     */
    public static boolean isDirExist(String directory, ChannelSftp sftp){
        Boolean isDirExistFlag = false;
        try {
            SftpATTRS attrs = sftp.lstat(directory);
            isDirExistFlag = true;
        } catch (SftpException e) {
        }
        return isDirExistFlag;
    }
    /**
     * @Description: 将本地工作站文件上传到对应的pas主机上
     * @author: feifei
     * @Date: 2019/8/15 13:57
     * @Param: directory
     * @Param: sftp
     * @Return: void
     */
    public static void createDir(String directory,ChannelSftp sftp){
        if(isDirExist(directory,sftp)){
            try {
                sftp.cd(directory);
                return;
            } catch (SftpException e) {
                e.printStackTrace();
            }
        }
        String[] dirArr = directory.split("/");
        StringBuffer filePath = new StringBuffer("/");
        try {
            for (String path : dirArr) {
                if (path.equals("")){
                    continue;
                }
                filePath.append(path+"/");
                if (!isDirExist(filePath.toString(),sftp)){
                    sftp.mkdir(filePath.toString());
                }
            }
            sftp.cd(directory);
        } catch (SftpException e) {
            e.printStackTrace();
        }

    }

}

  注意:这里是弄成sftp的方式,其他方式也可以通过这样的方式来实现。  

  四、Jsch中sftp提供的一些api

put():      文件上传
get():      文件下载
cd():       进入指定目录
ls():       得到指定目录下的文件列表
rename():   重命名指定文件或目录
rm():       删除指定文件
mkdir():    创建目录
rmdir():    删除目录
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值