코딩마을방범대

자바를 통해 서버에 파일 업로드&다운로드 하기 본문

💡 백엔드/Java

자바를 통해 서버에 파일 업로드&다운로드 하기

신짱구 5세 2024. 1. 23. 11:14

 

 

 

 

자바를 통해 서버의 sh 실행 제어하기

자바를 이용해 ssh 에 접속하여 command를 수행할 수 있다. 더불어 파일 업로드, 다운로드도 가능하다! 이번 포스팅에선 ssh에 접속해서 sh파일을 실행하는 로직을 구상해볼 것이다! 사용하기 1. 같은

sweet-rain-kim.tistory.com

 

이전 포스팅에선 sh 파일을 실행하는 로직을 구성해봤는데 이번 포스팅에선 파일 업로드&다운로드 로직을 테스트 해볼 것이다.

 

 

동일하게 JSch를 사용하기 위해 의존성 추가를 해준다.

dependencies {
	implementation 'com.jcraft:jsch:0.1.55'
}

 

 

세션 설정

public Session getSession(String host, String id, String password) throws JSchException {
	JSch jsch = new JSch();
	Session session = jsch.getSession(id, host, 22);
	session.setPassword(password);

	java.util.Properties config = new java.util.Properties();
	config.put("StrictHostKeyChecking", "no");
	session.setConfig(config);

	session.connect();
	return session;
}

 

 

 

 

 


 

 

 

 

 

 

파일 다운로드

 

1. 폴더 내 모든 파일 다운로드

public static void serverFileDownload(Session session, String serverDir, String localDir) throws SftpException {
	try {
		ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
		sftpChannel.connect();

		Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(serverDir);
		for (ChannelSftp.LsEntry entry : list) {
			if (entry.getAttrs().isDir()) {
				if (!(entry.getFilename().equals(".") || entry.getFilename().equals(".."))) {
					java.io.File localFile = new java.io.File(localDir + "/" + entry.getFilename());
					if (!localFile.exists()) {
						localFile.mkdir();
					}

					serverFileDownload(session, serverDir + "/" + entry.getFilename(), localDir + "/" + entry.getFilename());
				}
			} else {
				sftpChannel.get(serverDir + "/" + entry.getFilename(), localDir + "/" + entry.getFilename());
			}
		}

		sftpChannel.exit();
		session.disconnect();
	} catch (JSchException | SftpException e) {
		e.printStackTrace();
	}
}

 

 

 


 

 

 

2. 단일 파일 다운로드

public static void downloadSingleFile(Session session, String serverFilePath, String localDir) throws SftpException {
	ChannelSftp sftpChannel = null;
	try {
		sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
		
		sftpChannel.get(serverFilePath, localDir);	
	} catch (JSchException e) {
		e.printStackTrace();
	} finally {
		if (sftpChannel != null) {
			sftpChannel.exit();
		}
		if (session != null) {
			session.disconnect();
		}
	}
}

 

 

 

 

 

 

 


 

 

 

 

 

 

파일 업로드

 

1. 폴더 내 모든 파일 업로드

public static void uploadMultipleFiles(Session session, String localDirPath, String serverDir) throws SftpException {
	ChannelSftp sftpChannel = null;
	try {
		sftpChannel = (ChannelSftp) session.openChannel("sftp");
		sftpChannel.connect();

        // 로컬 디렉토리의 파일 리스트를 가져온다.
		java.io.File localDir = new java.io.File(localDirPath);
		java.io.File[] files = localDir.listFiles();

		if (files != null) {
			for (java.io.File file : files) {
				if (file.isFile()) { // 디렉토리가 아닌 파일인 경우에만 업로드
					// 각 파일을 서버로 업로드
					sftpChannel.put(file.getAbsolutePath(), serverDir + "/" + file.getName());
				}
			}
		}
	} catch (JSchException e) {
		e.printStackTrace();
	} finally {
		if (sftpChannel != null) {
			sftpChannel.exit();
		}
		if (session != null) {
			session.disconnect();
		}
	}
}

 

 

 


 

 

 

2. 단일 파일 업로드

public static void uploadSingleFile(Session session, String localFilePath, String serverDir) throws SftpException {
	ChannelSftp sftpChannel = null;
	try {
		// SFTP 채널을 연다
		sftpChannel = (ChannelSftp) session.openChannel("sftp");
		sftpChannel.connect();

		// 로컬 파일을 서버의 디렉토리로 업로드
		sftpChannel.put(localFilePath, serverDir);
	} catch (JSchException e) {
		e.printStackTrace();
	} finally {
		if (sftpChannel != null) {
			sftpChannel.exit();
		}
		if (session != null) {
			session.disconnect();
		}
	}
}

 

 

 

SMALL