주요글: 도커 시작하기
반응형


"[팁] j2ssh-maverick를 이용한 SCP + 키이용 파일 복사"에서 SCP 복사를 위해 j2ssh-maverick를 이용했는데, j2ssh-maverick를 이용해서 SFTP 파일 다운로드도 처리했다. 메이븐 의존 설정은 동일하니 이전글을 참고하면 된다.


SFTP로 특정 폴더의 전체 파일을 다운로드받는 코드는 다음과 같다. 아이디, 암호를 이용해서 인증을 처리했는데, 키파일을 이용하고 싶다면 이전글을 참고한다.


String host = "원격서버";

int port = 22;

String remoteUser = "download";


SshClient ssh = null;

try {

    SshConnector con = SshConnector.createInstance();

    ssh = con.connect(new SocketTransport(host, port), remoteUser);

    Ssh2PasswordAuthentication auth = new Ssh2PasswordAuthentication();

    auth.setUsername(remoteUser);

    auth.setPassword(password);

    int authResult = ssh.authenticate(auth);

    if (authResult != SshAuthentication.COMPLETE) {

        throw new RuntimeException("authFail = " + authResult);

    }

    SftpClient sftp = new SftpClient(ssh);

    sftp.setTransferMode(SftpClient.MODE_BINARY);

    FileTransferProgress progress = createFileTransferProgress();

    sftp.copyRemoteDirectory(

            "/home/download/files", // 다운로드할 원격 서버 폴더

            "/data/local/files", // 복사할 파일을 저장할 로컬 폴더 경로

            false, // recursive: true면 하위 폴더까지 포함

            false, // sync: 동기화 여부, true면 원격 폴더에 존재하지 않는 파일을 삭제

            true, // commit: true면 실제 작업을 수행

            progress); // 진척도를 통지받을 객체

    sftp.exit();

} catch (SshException | IOException | SftpStatusException | ChannelOpenException

        | TransferCancelledException e) {

    logger.error("fail to download", e);

    throw new RuntimeException(e);

} finally {

    if (ssh != null)

        try {

            ssh.disconnect();

        } catch (Exception ex) {

        }

}


progress를 생성할 때 사용한 createFileTransferProgress() 메서드는 다음과 같다. FileTransferProgress를 알맞게 구현하면 파일을 얼마나 다운로드했는지 추적할 수 있다.


private FileTransferProgress createFileTransferProgress() {

    return new FileTransferProgress() {

        @Override

        public void started(long bytesTotal, String remoteFile) {

            logger.info("download start: {}", remoteFile);

        }


        @Override

        public void progressed(long bytesSoFar) {

        }


        @Override

        public boolean isCancelled() {

            return false;

        }


        @Override

        public void completed() {

            logger.info("download done");

        }

    };

}


j2ssh-maverick를 사용하면 폴더 뿐만 아니라 개별 파일에 대한 업로드, 다운로드도 처리할 수 있다. j2ssh-maverick가 제공하는 다양한 기능은 https://github.com/sshtools/j2ssh-maverick에서 확인할 수 있다.

+ Recent posts