본문 바로가기
IT/Java

JSch 관련 (java 에서 ftp 사용)

by 성준하이 2023. 9. 14.
반응형

자바에서 서버에 붙는 작업을 하기 위해 ftp 를 사용하려 했고,

방법에 대해 공유한다.

 

먼저 JSch 관련 라이브러리를 받아야한다.

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

그리고 아래 함수를 사용해서 서버에 connect, disconnect, fileUpload, fileDownload 를 진행하면 된다.

 

connect
public void connectSFTP(String host, int port, String userName) throws Exception {
    JSch jsch = new JSch();

// JSch 세션 객체를 생성 (사용자 이름, 접속할 호스트, 포트 전달)
    jschSession = jsch.getSession(userName, host, port);

// 패스워드 설정시
    // jschSession.setPassword(password);
//rsa 키 사용시
    String key ="src/main/resources/id_rsa";
    jsch.addIdentity(key,"passphrase");

// 기타설정 적용
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    jschSession.setConfig(config);

// 접속
    jschSession.connect();

// sftp 채널 열기
    channel = jschSession.openChannel("sftp");

// sftp 채널 연결
    channelSftp = (ChannelSftp) channel;
    channelSftp.connect();
}

 

disconnect
public void disconnectSFTP() {
    try {
        if (channelSftp != null && channelSftp.isConnected()) {
            channelSftp.disconnect();
        }
    } catch (Exception e) {
    } finally {
        channelSftp = null;
    }

    try {
        if (channel != null && channel.isConnected()) {
            channel.disconnect();
        }
    } catch (Exception e) {
    } finally {
        channel = null;
}

    try {
        if (jschSession != null && jschSession.isConnected()) {
            jschSession.disconnect();
        }
    } catch (Exception e) {
    } finally {
        jschSession = null;
    }
}

 

fileupload
public boolean uploadFile(String fileName, String dirPath) throws Exception {

    boolean isSuccess = false;
    FileInputStream fis = null;


    try {
        channelSftp.cd(dirPath);
        File file = new File(fileName);
        fis = new FileInputStream(file);
        channelSftp.put(fis, file.getName());
        isSuccess = true;

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        close(fis);
    }

    return isSuccess;
}

 

filedownload
public boolean downloadFile(String remoteFilePath, String localDirPath, boolean overwrite) throws Exception {
    if (remoteFilePath == null || remoteFilePath.length() == 0) {
        return false;
    }

    boolean isSuccess = false;

    byte[] buffer = new byte[1024];

    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;

    try {
        if (remoteFilePath.indexOf("\\") > -1) {
            remoteFilePath = remoteFilePath.replace("\\", "/");
        }
        String remoteFileName = "";

        int lastSlashIndex = remoteFilePath.lastIndexOf("/");
        if (lastSlashIndex > -1) {
            String cdDir = remoteFilePath.substring(0, lastSlashIndex);
            remoteFileName = remoteFilePath.substring(lastSlashIndex + 1);
            channelSftp.cd(cdDir);
        } else {
            remoteFileName = remoteFilePath;
            channelSftp.cd("/");
        }

        File destFile = new File(localDirPath + File.separator + remoteFileName);
        if (destFile.exists()) {
            if (overwrite) {
                destFile.delete();
            } else {
                System.out.println("File Download canceled. File already exists : " + destFile.getAbsolutePath());
                return false;
            }
        }

// 파일 다운로드
        bis = new BufferedInputStream(channelSftp.get(remoteFileName));
        fos = new FileOutputStream(destFile);
        bos = new BufferedOutputStream(fos);
        int readCount = 0;
        while ((readCount = bis.read(buffer)) > 0) {
            bos.write(buffer, 0, readCount);
        }

        isSuccess = true;
        System.out.println("File downloaded : " + remoteFilePath + " => " + destFile.getAbsolutePath());

    }
catch (Exception e) {

        throw e;

    } finally {
        close(bos);
        close(fos);
        close(bis);
    }

    return isSuccess;
}

 

close 관련
/**
* FileInputStream 객체 닫기
*
* @param fis
*/
private void close(FileInputStream fis) {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e) {
} finally {
fis = null;
}
}


/**
* BufferedInputStream 객체 닫기
*
* @param bis
*/
private void close(BufferedInputStream bis) {
try {
if (bis != null) {
bis.close();
}
} catch (Exception e) {
} finally {
bis = null;
}
}


/**
* FileOutputStream 객체 닫기
*
* @param fos
*/
private void close(FileOutputStream fos) {


try {
if (fos != null) {
fos.flush();
}
} catch (Exception e) {
}


try {
if (fos != null) {
fos.close();
}
} catch (Exception e) {
} finally {
fos = null;
}
}


/**
* BufferedOutputStream 객체 닫기
*
* @param bos
*/
private void close(BufferedOutputStream bos) {


try {
if (bos != null) {
bos.flush();
}
} catch (Exception e) {
}


try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
} finally {
bos = null;
}
}

 

이렇게 하고 실제 사용 소스는 아래와 같다.

public static void main(String[] args) {
    JSchConfig jSchConfig = null;


    try {
        jSchConfig = new JSchConfig();


// SFTP 접속하기 (주소, 포트번호, 사용자아이디, 패스워드)
        jSchConfig.connectSFTP("1.2.3.4", 22, "test");


//파일을 다운로드 해서 해당파일 작업
        jSchConfig.downloadFile("/home/sungjun/main/study/sed.txt", "/Users/sungjun", false);


// 작업한 파일을 경로에 업로드
        jSchConfig.uploadFile("/Users/sungjun/test.txt", "/home/sungjun/main/study/test");

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
// SFTP 접속해제
        jSchConfig.disconnectSFTP();
    }
}
반응형

댓글