用java创造sftp连接到服务器代码

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SftpController {

    @GetMapping("/sftp")
    public ResponseEntity<String> getFileTree() {
        // 服务器地址
        String server = "your_server_address";
        // 用户名
        String username = "your_username";
        // 密码
        String password = "your_password";

        try (Session session = createSession(server, username, password)) {
            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            String fileTree = getFileTree(sftpChannel, "/");

            sftpChannel.disconnect();
            session.disconnect();

            return new ResponseEntity<>(fileTree, HttpStatus.OK);
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
            return new ResponseEntity<>("内部错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    public String getFileTree(ChannelSftp sftpChannel, String parentPath) throws SftpException {
        StringBuilder fileTree = new StringBuilder();
        try {
            java.util.Vector<ChannelSftp.LsEntry> entries = sftpChannel.ls(parentPath);
            for (ChannelSftp.LsEntry entry : entries) {
                String name = entry.getFilename();
                boolean isDirectory = entry.getAttrs().isDir();
                fileTree.append((isDirectory? "|-- " : "|-- ") + name + "\n");
                if (isDirectory &&!(".".equals(name) || "..".equals(name))) {
                    fileTree.append(getFileTree(sftpChannel, parentPath + "/" + name));
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
            throw new RuntimeException("获取文件树时出错", e);
        }
        return fileTree.toString();
    }

    @PostMapping("/sftp/upload")
    public ResponseEntity<String> uploadFile(@RequestHeader("FilePath") String filePath, InputStream inputStream) {
        // 服务器地址
        String server = "your_server_address";
        // 用户名
        String username = "your_username";
        // 密码
        String password = "your_password";

        try (Session session = createSession(server, username, password)) {
            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            sftpChannel.put(inputStream, filePath);

            sftpChannel.disconnect();
            session.disconnect();

            return new ResponseEntity<>("上传成功", HttpStatus.OK);
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
            return new ResponseEntity<>("上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/sftp/download")
    public ResponseEntity<byte[]> downloadFile(String filePath) {
        // 服务器地址
        String server = "your_server_address";
        // 用户名
        String username = "your_username";
        // 密码
        String password = "your_password";

        try (Session session = createSession(server, username, password)) {
            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            byte[] fileData = new byte[0];
            try (OutputStream outputStream = new java.io.FileOutputStream("tempFile")) {
                sftpChannel.get(filePath, outputStream);
                fileData = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get("tempFile"));
            } catch (SftpException | NoSuchFileException | IOException e) {
                e.printStackTrace();
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }

            sftpChannel.disconnect();
            session.disconnect();

            return new ResponseEntity<>(fileData, HttpStatus.OK);
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private Session createSession(String server, String username, String password) throws JSchException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, server, 22);
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        return session;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值