[JAVA] Spring SSH sftp 파일 다운로드(apache.sshd)

2025. 1. 20. 15:10·[JAVA]
반응형

jsch 구현된 코드가 안 되면서 최근 apache의 Mina-sshd 로 변환중이다.

sftp 파일 다운로드 코드.

 

 

Dependency

버전 맞춰줘야 오류 안 나는듯

implementation 'org.apache.sshd:sshd-core:2.12.0'
implementation 'org.apache.sshd:sshd-sftp:2.12.0'

 

 

Code

package com.aspnrpa.test;


import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.config.keys.FilePasswordProvider;
import org.apache.sshd.common.config.keys.loader.KeyPairResourceLoader;
import org.apache.sshd.common.util.security.SecurityUtils;
import org.apache.sshd.sftp.client.SftpClient;
import org.apache.sshd.sftp.client.SftpClientFactory;

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.util.Collection;

public class TestService {

    public void download(String robotName,String localFilePath, String remoteFilePath) {

        String host = "ex:";
        int port = 22;
        String username = "ex:user";
        String privateKeyPath = "ex:C:\\Users\\User\\.ssh\\id_rsa";
        String password = null;

        
        try (SshClient client = SshClient.setUpDefaultClient()) {

            client.start();

            KeyPairResourceLoader loader = SecurityUtils.getKeyPairResourceParser();
            Path path = Paths.get(privateKeyPath);
            Collection<KeyPair> keys = loader.loadKeyPairs(null, path, FilePasswordProvider.of(password));

            try (ClientSession session = client.connect(username, host, port)
                    .verify(10000)
                    .getSession()) {
                session.addPublicKeyIdentity(keys.iterator().next());
                session.auth().verify(10000);

                try (SftpClient sftp = SftpClientFactory.instance().createSftpClient(session)) {
                    try (OutputStream os = Files.newOutputStream(Paths.get(localFilePath));
                         SftpClient.CloseableHandle handle = sftp.open(remoteFilePath)) {
                        byte[] buffer = new byte[8192];
                        long offset = 0;
                        while (true) {
                            int len = sftp.read(handle, offset, buffer, 0, buffer.length);
                            if (len == -1) {
                                break;
                            }
                            os.write(buffer, 0, len);
                            offset += len;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Download completed");
    }
}

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'[JAVA]' 카테고리의 다른 글

[JAVA] com.jcraft.jsch.JSchException: Auth fail (apache로 변경)  (0) 2025.01.13
[Web][Error] Ubuntu 에서 H2 로그인 시 “사이트에 연결할 수 없음”  (0) 2024.04.02
[JAVA] Maven Repository Path(\.m2)  (0) 2024.04.02
[JAVA]ERROR: JAVA_HOME is set to an invalid directory  (2) 2023.12.05
[JAVA] IntelliJ 유용한 단축키 모음  (0) 2022.02.15
'[JAVA]' 카테고리의 다른 글
  • [JAVA] com.jcraft.jsch.JSchException: Auth fail (apache로 변경)
  • [Web][Error] Ubuntu 에서 H2 로그인 시 “사이트에 연결할 수 없음”
  • [JAVA] Maven Repository Path(\.m2)
  • [JAVA]ERROR: JAVA_HOME is set to an invalid directory
jkod
jkod
  • jkod
    개발린이
    jkod
  • 반응형
    • 분류 전체보기
      • [RPA]
      • [Python]
      • [VBA]
      • [JAVA]
      • [Window]
      • [MAC]
      • [기타]
        • 생활
  • 최근 글

  • 인기 글

  • hELLO· Designed By정상우.v4.10.2
jkod
[JAVA] Spring SSH sftp 파일 다운로드(apache.sshd)
상단으로

티스토리툴바