본문 바로가기

IT, 개발/JAVA

자바 파일 전송 - JSch을 활용한 SFTP 파일 업로드

728x90
반응형

 

 

 

 

 

프로그램을 개발하다 보면 서버나 클라이언트 간 통신뿐만 아니라 파일을 업로드하는 기능도 필요할 때가 있습니다.
그럴 때 간단하게 FTP로 파일을 업로드하는 기능을 알아보도록 하겠습니다.

우선 FTP 업로드 시 필요한 정보는

1. 전송받을 서버의 정보(IP 계정, 비밀번호 등)
2. 전송받을 서버 측 파일 저장할 경로
3. 보내는 측(로컬) 파일의 경로 

 

그리고 로컬에서 경로(localPath)를 지정할 때 파일을 지정하여 경로를 설정합니다.
파일을 여러 개 전송하고자 할 경우에는 /*.txt 와 같이 설정하여 사용할 수도 있습니다. (폴더 내 txt 파일 전체 전송) 

 

예제를 보시고 테스트해보시기 바랍니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.Properties;
 
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
 
public class TestFTP {
    
    // 접속할 ip, port, username, password 
    String sftpIp = "192.168.123.123";
    int sftpPort = 22;
    String sftpUsername = "username";
    String sftpPassword = "password";
    
    // 보낼 파일 경
    String localPath = "/home/testpath/test.txt";
    
    // 접속하려는 곳에서 파일 받을 경로 
    String remotePath = "/home/remotepath/";
    
    
    
    public void sftpUploadTest() throws Exception
    {
        // JSch 객체 생성
        JSch jsch = new JSch();
        
        // 세션 객체 생성 
        // 접속할 ip, port, username, password 설정 
        Session session;
        session = jsch.getSession(sftpUsername, sftpIp, sftpPort);
        session.setPassword(sftpPassword);
        
        // ssh_config에 호스트 key없이 접속 가능하도록 property 설정
        Properties config = new Properties();
        config.put("StrictHostKeyChecking""no");
        session.setConfig(config);
        
        // 접속 
        session.connect();
        
        
        ChannelSftp channelSftp = null;
        Channel channel = null;
        
        try 
        {
            // sftp 채널 오픈 & 연결 
            channel = session.openChannel("sftp");
            channel.connect();
            
            channelSftp = (ChannelSftp) channel;
            channelSftp.put(localPath, remotePath);
        } 
        catch(Exception e) 
        {
            // 예외 처리 
            // 
            
        }
        finally
        {
            // 완료 후 접속 종료 
            channelSftp.disconnect();
            channel.disconnect();
            session.disconnect();
        }
    }
    
}
cs

 

 

 

 

 

 

728x90
반응형