当前位置: 首页 > 工具软件 > JSch > 使用案例 >

JSCH连接SFTP服务器

端木承业
2023-12-01

1、添加依赖jsch依赖

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

2、工具类示例

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;

@Slf4j
public class SFTPUtil {
    private String host;
    private int port;//没有特别配置 默认22
    private String username;
    private String password;
    private String rootPath;
    private ChannelSftp sftpChannel;

    public SFTPUtil(String host, int port, String username, String password, String rootPath) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.rootPath = rootPath;
    }

    /**
     * 连接
     */
    public void connect() {
        if (sftpChannel == null || sftpChannel.isClosed()) {
            JSch jSch = new JSch();
            Session sshSession = null;
            try {
                sshSession = jSch.getSession(username, host, port);
                sshSession.setPassword(password);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sshSession.setConfig(sshConfig);
                sshSession.setTimeout(300000);
                sshSession.connect();
                Channel channel = sshSession.openChannel("sftp");
                channel.connect();
                sftpChannel = ((ChannelSftp) channel);
                log.info("channelStatus:->{}", sftpChannel.isConnected());
                try {
                    sftpChannel.setFilenameEncoding("UTF-8");
                } catch (SftpException e) {
                    e.printStackTrace();
                }
            } catch (JSchException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        if (sftpChannel != null) {
            try {
                Session sshSession = sftpChannel.getSession();
                if (sshSession.isConnected()) {
                    sshSession.disconnect();
                }
            } catch (JSchException e) {
                e.printStackTrace();
            }
            sftpChannel.disconnect();
        }
    }

    public InputStream getInputStream(String fileName) {
        InputStream inputStream = null;
        if (!this.rootPath.endsWith("/")) {
            this.rootPath += "/";
        }
        try {
            String fullPath = rootPath + fileName;
            try {
                this.sftpChannel.cd(fullPath.substring(0, fullPath.lastIndexOf("/")));
            } catch (Exception e) {
                this.sftpChannel.cd(fileName.substring(0, fileName.lastIndexOf("/")));
            }
            inputStream = this.sftpChannel.get(fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return inputStream;
    }

    public boolean exists(String fileName) {
        boolean exists = false;
        if (!this.rootPath.endsWith("/")) {
            this.rootPath += "/";
        }
        try {
            log.info("Exists RootPath:->{},channelStatus:->{}", rootPath, sftpChannel.isConnected());
            Vector<ChannelSftp.LsEntry> resVe = this.sftpChannel.ls(rootPath);
            for (ChannelSftp.LsEntry s : resVe) {
                if (s.getFilename().equalsIgnoreCase(fileName)) {
                    exists = true;
                    break;
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return exists;
    }
}

注意事项:
如果端口没有特别配置,SFTP服务器端口默认为:22

高质量博文-wiliam-me

 类似资料: