설정소스
public class SFTPConfig {
public static final Stringhost= "13.124.251.220";
public static final StringuserName= "ec2-user";
public static final intport= 22;
public static final StringprivateKey= "/Users/leeseokwoon/Documents/lee.pem";
}
SFTP 접속에 필요한 정보들을 파라미터로 받아 실제 채널 접속하는 로직.
public void init(String host, String userName, String password, Integer port, String privateKey) {
JSch jSch = new JSch();
try {
if(privateKey != null) {//개인키가 존재한다면
jSch.addIdentity(privateKey);
}
session = jSch.getSession(userName, host, port);
if(privateKey == null && password != null) {//개인키가 없다면 패스워드로 접속
session.setPassword(password);
}
// 프로퍼티 설정
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no"); // 접속 시 hostkeychecking 여부
session.setConfig(config);
session.connect();
//sftp로 접속
channel = session.openChannel("sftp");
channel.connect();
} catch (JSchException e) {
e.printStackTrace();
}
channelSftp = (ChannelSftp) channel;
}
삭제 된 폴더 또는 파일은 백업 대상에서 제외해야함
public void run(String sourcePath, String destinationPath) throws SftpException, FileNotFoundException {
//업로드 전 이전 폴더 삭제후 재생성
//destinationPath 이전 디렉터리
//생성할 디렉터리
String dirName = destinationPath+sourcePath.substring(sourcePath.lastIndexOf("/")+1);
if(exists(dirName)){
//sourcePath 마지막 경로 뺴오기
rmdir(dirName);
//업로드 대상경로도 삭제
channelSftp.rmdir(dirName);
// mkdir(dirName);
}else{
mkdir(dirName);
}
recursiveFolderUpload(sourcePath,destinationPath);
}
삭제 폴더 내 파일 또는 폴더가 있을경우 단순 rm 명령어로는 삭제가 안됨.
재귀 함수를 이용해 폴더 내 파일 또는 하위폴더 삭제
public void rmdir(String dir) throws SftpException {
// 폴더안에 파일이 있을경우 파일들을 삭제
Vector fileList = channelSftp.ls(dir);
for (int i = 0; i < fileList.size(); i++) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) fileList.get(i);
//검색된 .(현재경로)..(이전경로)는 continue
if (entry.getFilename().equals(".") || entry.getFilename().equals("..")) {
continue;
}
//검색된게 폴더일경우 재귀함수로 들어가서 파일들을 삭제
if (entry.getAttrs().isDir()) {
rmdir(dir + "/" + entry.getFilename());
//폴더 내 파일들을 삭제 완료했을경우
channelSftp.rmdir(dir + "/" + entry.getFilename());
}
//검색된게 파일일경우 파일 삭제
else {
channelSftp.rm(dir + "/" + entry.getFilename());
}
}
}
private void recursiveFolderUpload(String sourcePath, String destinationPath)
throws SftpException, FileNotFoundException {
File sourceFile = new File(sourcePath);
//sourceFile이(백업대상) 파일인경우
if (sourceFile.isFile()) {
//업로드 대상경로로 이동
channelSftp.cd(destinationPath);
// "."일경우 (숨김폴더) 업로드하지않음
if (!sourceFile.getName().startsWith("."))
channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
}
//sourceFile이(백업대상) 폴더인경우
else {
// sourceFile.isFile() == false 일경우 디렉토리
System.out.println("inside else " + sourceFile.getName());
//해당 sourceFile에 대한 파일 또는 폴더목록 배열화
File[] files = sourceFile.listFiles();
if (files != null && !sourceFile.getName().startsWith(".")) {
//업로드 대상경로로 이동
channelSftp.cd(destinationPath);
SftpATTRS attrs = null;
// check if the directory is already existing
try {
//해당 디렉토리가 존재하는지 확인
attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
}
// 해당 디렉토리가 존재하지 않는다면 attrs = null
catch (Exception e) {
System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
}
// attrs가 null이 아닐경우 (디렉토리가 존재할경우)
if (attrs != null) {
System.out.println("Directory exists IsDir=" + attrs.isDir());
}
// attrs가 null일경우 (디렉토리가 존재하지않을경우)
else {
System.out.println("Creating dir " + sourceFile.getName());
channelSftp.mkdir(sourceFile.getName());
}
// 업로드 대상 파일 배열화 후 재귀함수 이용해 업로드 진행
for (File f : files) {
recursiveFolderUpload(f.getAbsolutePath(), destinationPath + "/" + sourceFile.getName());
}
}
}
}