1. 개요

이 사용방법(예제)에서는 Java에서 SFTP를 사용하여 원격 서버에서 파일을 업로드 및 다운로드하는 방법에 대해 설명합니다 .

JSch, SSHJ 및 Apache Commons VFS의 세 가지 라이브러리를 사용합니다.

2. JSch 사용하기

먼저 JSch 라이브러리를 사용하여 원격 서버에서 파일을 업로드 및 다운로드하는 방법을 알아보겠습니다.

2.1. 메이븐 구성

pom.xml 에 jsch 의존성을 추가해야 합니다 .

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

최신 버전의 jsch 는 Maven Central 에서 찾을 수 있습니다 .

2.2. JSch 설정

이제 JSch를 설정하겠습니다.

JSch를 사용하면 암호 인증 또는 공개 키 인증을 사용하여 원격 서버에 액세스할 수 있습니다. 이 예에서는 비밀번호 인증을 사용합니다 .

private ChannelSftp setupJsch() throws JSchException {
    JSch jsch = new JSch();
    jsch.setKnownHosts("/Users/john/.ssh/known_hosts");
    Session jschSession = jsch.getSession(username, remoteHost);
    jschSession.setPassword(password);
    jschSession.connect();
    return (ChannelSftp) jschSession.openChannel("sftp");
}

위의 예에서 remoteHost 는 원격 서버의 이름 또는 IP 주소(예: example.com )를 나타냅니다. 테스트에 사용된 변수를 다음과 같이 정의할 수 있습니다.

private String remoteHost = "HOST_NAME_HERE";
private String username = "USERNAME_HERE";
private String password = "PASSWORD_HERE";

다음 명령을 사용하여 known_hosts 파일을 생성할 수도 있습니다 .

ssh-keyscan -H -t rsa REMOTE_HOSTNAME >> known_hosts

2.3. JSch로 파일 업로드

원격 서버에 파일을 업로드하려면 ChannelSftp.put() 메서드를 사용합니다 .

@Test
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
 
    String localFile = "src/main/resources/sample.txt";
    String remoteDir = "remote_sftp_test/";
 
    channelSftp.put(localFile, remoteDir + "jschFile.txt");
 
    channelSftp.exit();
}

이 예에서 메소드의 첫 번째 매개변수는 전송할 로컬 파일인 src/main/resources/sample.txt를 나타내며 remoteDir 은 원격 서버의 대상 디렉토리 경로입니다.

2.4. JSch로 파일 다운로드

ChannelSftp.get() 을 사용하여 원격 서버에서 파일을 다운로드 할 수도 있습니다 .

@Test
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
 
    String remoteFile = "welcome.txt";
    String localDir = "src/main/resources/";
 
    channelSftp.get(remoteFile, localDir + "jschFile.txt");
 
    channelSftp.exit();
}

remoteFile 은 다운로드할 파일의 경로이고  localDir  대상 로컬 디렉터리의 경로를 나타냅니다.

3. SSHJ 사용

다음으로 SSHJ 라이브러리를 사용하여 원격 서버에서 파일을 업로드 및 다운로드합니다.

3.1. 메이븐 구성

먼저 pom.xml 에 의존성을 추가합니다 .

<dependency>
    <groupId>com.hierynomus</groupId>
    <artifactId>sshj</artifactId>
    <version>0.27.0</version>
</dependency>

최신 버전의 sshj 는 Maven Central 에서 찾을 수 있습니다 .

3.2. SSHJ 설정

그런 다음 SSHClient 를 설정합니다 .

SSHJ를 사용하면 암호 또는 공개 키 인증을 사용하여 원격 서버에 액세스할 수도 있습니다.

이 예에서는 비밀번호 인증을 사용합니다.

private SSHClient setupSshj() throws IOException {
    SSHClient client = new SSHClient();
    client.addHostKeyVerifier(new PromiscuousVerifier());
    client.connect(remoteHost);
    client.authPassword(username, password);
    return client;
}

3.3. SSHJ로 파일 업로드

JSch와 유사하게 SFTPClient.put() 메서드를 사용 하여 원격 서버에 파일을 업로드합니다 .

@Test
public void whenUploadFileUsingSshj_thenSuccess() throws IOException {
    SSHClient sshClient = setupSshj();
    SFTPClient sftpClient = sshClient.newSFTPClient();
 
    sftpClient.put(localFile, remoteDir + "sshjFile.txt");
 
    sftpClient.close();
    sshClient.disconnect();
}

여기에 정의할 두 개의 새로운 변수가 있습니다.

private String localFile = "src/main/resources/input.txt";
private String remoteDir = "remote_sftp_test/";

3.4. SSHJ로 파일 다운로드

원격 서버에서 파일을 다운로드할 때도 마찬가지입니다. 우리는 SFTPClient.get() 을 사용할 것입니다 :

@Test
public void whenDownloadFileUsingSshj_thenSuccess() throws IOException {
    SSHClient sshClient = setupSshj();
    SFTPClient sftpClient = sshClient.newSFTPClient();
 
    sftpClient.get(remoteFile, localDir + "sshjFile.txt");
 
    sftpClient.close();
    sshClient.disconnect();
}

그리고 위에서 사용된 두 개의 변수를 추가합니다.

private String remoteFile = "welcome.txt";
private String localDir = "src/main/resources/";

4. Apache Commons VFS 사용

마지막으로 Apache Commons VFS를 사용하여 파일을 원격 서버로 전송합니다.

사실 Apache Commons VFS는 내부적으로 JSch 라이브러리를 사용합니다 .

4.1. 메이븐 구성

pom.xml 에 commons-vfs2 의존성 을 추가해야 합니다 .

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-vfs2</artifactId>
    <version>2.4</version>
</dependency>

commons-vfs2 의 최신 버전은 Maven Central 에서 찾을 수 있습니다 .

4.2. Apache Commons VFS로 파일 업로드

Apache Commons VFS는 약간 다릅니다.

FileSystemManager사용하여 대상 파일에서 FileObject 를 만든 다음 FileObject를 사용하여 파일 전송합니다.

이 예에서는 FileObject.copyFrom() 메서드를 사용하여 파일을 업로드합니다 .

@Test
public void whenUploadFileUsingVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
 
    FileObject local = manager.resolveFile(
      System.getProperty("user.dir") + "/" + localFile);
    FileObject remote = manager.resolveFile(
      "sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
 
    remote.copyFrom(local, Selectors.SELECT_SELF);
 
    local.close();
    remote.close();
}

로컬 파일 경로는 절대 경로여야 하고 원격 파일 경로는 sftp://username: password@remoteHost로 시작해야 합니다.

4.3. Apache Commons VFS로 파일 다운로드

원격 서버에서 파일을 다운로드하는 것은 매우 유사합니다. 또한 FileObject.copyFrom() 을 사용하여 remoteFile 에서 localFile복사 합니다 .

@Test
public void whenDownloadFileUsingVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
 
    FileObject local = manager.resolveFile(
      System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
    FileObject remote = manager.resolveFile(
      "sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
 
    local.copyFrom(remote, Selectors.SELECT_SELF);
 
    local.close();
    remote.close();
}

5. 결론

이 기사에서는 Java로 원격 SFTP 서버에서 파일을 업로드하고 다운로드하는 방법을 배웠습니다. 이를 위해 JSch, SSHJ 및 Apache Commons VFS와 같은 여러 라이브러리를 사용했습니다.

전체 소스 코드는 GitHub 에서 찾을 수 있습니다 .

Generic footer banner