2018년 11월 5일 월요일

[JaVa] SFTP Upload

1. 필요 라이브러리

compile('com.jcraft:jsch:0.1.54') 

* 최신 버젼은 maven repository 에서 확인 가능.


2. 테스트 코드
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 MyTest  {

/**
* SFTP Upload -> 게시물 원본 http://javacpro.tistory.com/22 참고
* */
public void sftpUploadTest() {

Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;

// SFTP 서버연결
String url = "192.168.0.100";
String user = "YOUR_SFTP_USER_ID";
String password = "YOUR_SFTP_USER_PASSWORD";
int port = 1234;
File uploadFile = new File("D:\\SFTP_UPLOAD_FILE.EXT");

// JSch 객체 생성
JSch jsch = new JSch();
try {
// 세션객체 생성 ( user , host, port )
session = jsch.getSession(user, url, port);
session.setPassword(password);

// 세션관련 설정정보 설정
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no"); // 호스트 정보 검사하지 않는다.
session.setConfig(config);
session.connect();

// sftp 채널 접속
channel = session.openChannel("sftp");
channel.connect();

} catch (JSchException e) {
// e.printStackTrace();
System.out.println(e.toString());
}

channelSftp = (ChannelSftp) channel;

// upload("./dat/", new File("C:\\Users\\jhkim1981\\Desktop\\20181102_TEST_UPLOAD.txt"));

FileInputStream in = null;
        try{ //파일을 가져와서 inputStream에 넣고 저장경로를 찾아 put
        in = new FileInputStream(uploadFile);
            channelSftp.cd("/home/freecatz/upload");
            channelSftp.put(in, uploadFile.getName());
        }catch(SftpException e){
// e.printStackTrace();
        System.out.println(e.toString());
        }catch(FileNotFoundException e){
// e.printStackTrace();
        System.out.println(e.toString());
        }finally{
            try{
                in.close();
            } catch(IOException e){
//    e.printStackTrace();
            System.out.println(e.toString());
            }
        }
   }


}

댓글 없음 :

댓글 쓰기