sftp

2022. 2. 10. 19:01spring

package ocps.portal.exchange.usecase.send;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SftpUpload {

	private Session jschSession = null;
	private Channel channel = null;
	private ChannelSftp channelSftp = null;

	/**
	 * sftp 접속
	 * 
	 * @param sftpIp
	 * @param sftpPort
	 * @param sftpId
	 * @param sftpPassword
	 * @throws Exception
	 */
	public void connectSFTP(String sftpIp, int sftpPort, String sftpId, String sftpPassword) throws Exception {

		try {

			// JSch 객체 생성
			JSch jsch = new JSch();

			// JSch 세션 객체 생성
			jschSession = jsch.getSession(sftpId, sftpIp, sftpPort);

			// 패스워드 설정
			jschSession.setPassword(sftpPassword);

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

			// sftp 접속
			jschSession.connect();

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

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

			log.info("########## sftp connect success ##########");

		} catch (Exception e) {
			log.error("########## sftp connect fail ##########");
		}

	}

	/**
	 * sftp 접속 해제
	 * 
	 */
	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;
		}

		log.info("########## sftp disconnect ##########");
	}

	/**
	 * 파일 업로드
	 * 
	 * @param fileName
	 * @param dirPath
	 * @return
	 * @throws Exception
	 */
	public void uploadFile(String sendTempDir, String receiveDir, String fileName) throws Exception {

		FileInputStream fis = null;

		try {

			try {
				// 대상 폴더 이동
				channelSftp.cd(receiveDir);
			} catch (Exception e) {
				// 대상 폴더 없을 경우, 대성폴더 생성
				mkdir(receiveDir);
				// 대상 폴더 생성할 경우 재지정
				channelSftp.cd(receiveDir);
			}

			if (!sendTempDir.endsWith("/")) {
				sendTempDir += "/";
			}

			if (!receiveDir.endsWith("/")) {
				receiveDir += "/";
			}

			// 파일 업로드
			File file = new File(sendTempDir + fileName);
			fis = new FileInputStream(file);
			channelSftp.put(fis, file.getName());
			log.info("########## File upload : " + file.getAbsolutePath() + " => " + receiveDir + file.getName());

		} catch (Exception e) {
			log.error("########## File upload fail : " + sendTempDir + fileName + " => " + receiveDir + fileName);
		} finally {
			fis.close();
		}

	}

	/**
	 * 폴더 생성
	 * 
	 * @param dirPath
	 * @param dirName
	 * @return
	 * @throws Exception
	 */
	public void mkdir(String dirPath) throws Exception {
		String[] dirPathArr = dirPath.split("/");
		String newDir = "";
		for (int i = 0; i < dirPathArr.length; i++) {
			if (!newDir.endsWith("/")) {
				newDir += "/";
			}
			newDir += dirPathArr[i];
			try {
				channelSftp.cd(newDir);
				channelSftp.cd(newDir);
			} catch (Exception e) {
				channelSftp.mkdir(newDir);
				log.info("########## crate directory -----> " + newDir);
			}
		}
	}

}


http://it-archives.com/222343809100/

[JAVA] 자바 SFTP 파일 업로드, 파일 다운로드 (jsch 라이브러리 사용방법) – 흑곰의 유익한 블로그 2

[JAVA] 자바 SFTP 파일 업로드, 파일 다운로드 (jsch 라이브러리 사용방법) 자바 FTP 파일 업로드, 다운로드를 구현하기 위해서 ​FTPSClient 사용하려고 했는데(관련 라이브러리 파일은 commons-net-2.2.jar)

it-archives.com