type
Post
status
Published
t-status
complete
date
Mar 20, 2019
slug
summary
sftp 로 서버에 접속하여 특정 폴더를 tar로 압축 하기
tags
Spring
Java
main-category
Language
category
Java
icon
password
개발환경
- Spring FrameWork
적용
- 라이브러리 추가
pom.xml 파일 내용 추가하여 라이브러리 받는다.
<!-- FTP (sftp,ssh) --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.50</version> </dependency>
- JAVA 소스 작성
String filePath = "/home/test.tar"; //결과물 File tarfile = new File(filePath); final OutputStream os = new FileOutputStream(tarfile); TarOutputStream tos = new TarOutputStream(os); JSch jsch = new JSch(); Session sftpSession = jsch.getSession(<접속Id>,<접속Ip>,22); sftpSession.setPassword(<접속pw>); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); sftpSession.setConfig(config); sftpSession.connect(); String targetDir = <압축할 폴더 경로>; Channel channel = sftpSession.openChannel("sftp"); channel.connect(); ChannelSftp channelSftp = (ChannelSftp) channel; Vector<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(targetDir); for(ChannelSftp.LsEntry item : fileAndFolderList){ if(!item.getAttrs().isDir()){ // 폴더는 다운 안받을거임, 폴더도 압축할경우 메서드로 뺀뒤 사용 InputStream is = channelSftp.get(targetDir+item.getFilename()); byte[] buff = null; buff = IOUtils.toByteArray(is); int bufferSize = buff.length; TarEntry entry = new TarEntry(item.getFilename()); entry.setSize(bufferSize); tos.putNextEntry(entry); tos.write(buff,0,bufferSize); tos.closeEntry(); is.close(); } } if (channelSftp != null) channelSftp.disconnect(); if (channel != null) channel.disconnect(); if (session != null) sftpSession.disconnect(); tos.close(); os.close();