SFTP 실행 예제
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SFTPClient {
//private static final int BUFFER_SIZE = 4096;
private String server; // 도착지 IP
private int port = 22; // SFTP 기본포트
private String username; // 사용자명
private String password; // 사용자 비밀번호
private JSch jsch;
private Session session;
private Channel channel;
private ChannelSftp channelSftp;
public SFTPClient(String server, String username, String password){
this.jsch = new JSch();
this.server = server;
this.username = username;
this.password = password;
}
public void connect() throws JSchException {
System.out.println("connecting server ....." + server);
try {
// 세션객체 생성
session = jsch.getSession(username, server, port);
//패스워드 설정
session.setPassword(password);
// 세션설정 정보설정
java.util.Properties config = new java.util.Properties();
//호스트검사 X
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// 서버 접속
session.connect();
//SFTP CHANNEL OPEN
channel = session.openChannel("sftp");
// 채널 연결
channel.connect();
System.out.println("connecting SECCESS ....." + server);
} catch (JSchException e) {
System.out.println("connecting FAILD ....." + server);
e.printStackTrace();
}
//System.out.println(channel);
channelSftp = (ChannelSftp) channel;
}
/*
*
* Parameter
*
* file : 전송할 FILE
* fileName : 파일명
* fptpath : 전송할 경로
*
* */
public String upload(File file, String fileName, String ftpPath) throws SocketException, IOException{
String result = "fail";
FileInputStream in;
try {
connect(); // 서버 및 SFTP 채널 연결
System.out.println("======== Upload File " + file.getPath() + " at " + server + " in " + ftpPath + " START");
//System.out.println(ftpPath);
in = new FileInputStream(file);
//디렉토리 변경
channelSftp.cd(ftpPath);
// 업로드
channelSftp.put(in, fileName);
result = "SUCCESS";
in.close();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
//CONNECT 실패시를 위한 Ex
e.printStackTrace();
}
System.out.println("======= Uploaded : " + file.getPath() + " at " + server);
return result;
}
// 파일서버 및 세션종료
public void disconnect(){
channelSftp.quit();
session.disconnect();
}
}