자바 다른 서버로 sftp 파일 전송

개발/코딩 2020. 3. 23. 13:19

sftp를 활용하기 위해서는 jsch 라이브러리가 필요.

 

*maven 형태 

<dependency>

<groupId>com.jcraft</groupId>

<artifactId>jsch</artifactId>

<version>0.1.55</version>

</dependency>

 

*gradle 형태

// https://mvnrepository.com/artifact/com.jcraft/jsch

compile group: 'com.jcraft', name: 'jsch', version: '0.1.55'

 

해당 클래스에 

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

 

프로세스를 작성한후 

sftpConnect(fileName); 호출 하면

 

  // 다른서버 SSH 전송
@SuppressWarnings("finally")
public String sftpConnect(String fileName) {
    String rfileName = "";
    try {
    String des = "/root/"; //파일을 이동시키고자 하는 위치
    String src = "/home/tomcat/webapps/Anticall/upload/";  //파일이 존재 하는 위치
JSch jsch = new JSch();
Session session = jsch.getSession("user", "192.168.xxx.xxx", 22);  //user, ip, port
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");  //이동시킬 서버의 password

session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.cd(des); 
File file = new File(src+fileName);
FileInputStream fis = new FileInputStream(file);
sftpChannel.put(fis, file.getName());
fis.close();

sftpChannel.disconnect();
channel.disconnect();
session.disconnect();   

rfileName = file.getName();
} catch(Exception e) {
logger.error("Exception:",e);
} finally {
return rfileName;
}   
}