[java] JSch 라이브러리 & DH 알고리즘 사용하여, java sftp client 환경 구축하는 방법.(*.java, sftp client code)

2022. 3. 25. 17:04Language/java

728x90
728x90

JSch 라이브러리 & DH 알고리즘 사용하여, java sftp client 환경 구축 & java sftp client에서 sftp server 접속하는 방법.(*.java, sftp client 코드)


1.하단의 링크 접속 JSch 라이브러리 다운로드


2.하단의 링크 접속 jdk 버전에 맞는 bouncycastle 라이브러리 다운로드


3.eclipse에서 sftp client 프로젝트 생성.


4.생성한 프로젝트 -> properties -> Java Build Path -> Add External JARs … -> 다운로드한 JSch & bouncycastle 라이브러리 추가.


5.Referenced Libraries에서 추가된 라이브러리 확인.


6.JSch 라이브러리 & DH 알고리즘(DiffieHellman key exchange) 사용하여, sftp client code 작성.(코드 참고 http://thefif19wlsvy.tistory.com/2)

package sftp_client;

import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Scanner;
import java.util.Vector;
import javax.crypto.KeyAgreement;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
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 {
	public sftpClient() {
	}

	public static void main(String[] args) {
		Security.addProvider(new BouncyCastleProvider());
		try {
			KeyPairGenerator.getInstance("DH");
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		try {
			KeyAgreement.getInstance("DH");
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}

		Session session = null;
		Channel channel = null;
		JSch jsch = new JSch();
		Scanner scanner = new Scanner(System.in);

		System.out.print("계정 입력: ");
		String username = scanner.nextLine();
		System.out.print("호스트 주소 입력: ");
		String host = scanner.nextLine();
		System.out.print("비밀번호 입력: ");
		String password = scanner.nextLine();

		try {
			// 세션 객체 생성
			session = jsch.getSession(username, host, 22);
			// 비밀번호설정
			session.setPassword(password);
			// 호스트 정보를 검사하지 않음
			session.setConfig("StrictHostKeyChecking", "no");
			// 세션접속
			session.connect();
			// sftp채널열기
			channel = session.openChannel("sftp");
			// 채널접속
			channel.connect();
			System.out.println("Connected to user@" + host);
		} catch (JSchException e) {
			e.printStackTrace();
			System.out.println("접속에 실패했습니다.");
			// 실패시 시스템 종료
			System.exit(0);
		}

		ChannelSftp channelSftp = (ChannelSftp) channel;

		while (true) {
			System.out.print("sftp> ");
			String str = "";
			str = scanner.nextLine();

			String[] params = str.split(" ");
			String command = params[0];

			if (command.equals("cd")) {
				String p1 = params[1];
				try {
					channelSftp.cd(p1);
				} catch (SftpException e) {
					System.out.println("Couldn't stat remote file: No such file or directory");
				}
			}
			// end cd
			else if (command.equals("lcd")) {
				String p1 = params[1];
				try {
					channelSftp.lcd(p1);
				} catch (SftpException e) {
					System.out.println("Couldn't change local directory to " + p1 + ": No such file or directory");
				}
			}
			// end lcd
			else if (command.equals("pwd")) {
				try {
					System.out.println("Remote working directory: " + channelSftp.pwd());
				} catch (SftpException e) {
					e.printStackTrace();
				}
			}
			// end pwd
			else if (command.equals("lpwd")) {
				System.out.println("Local working directory: " + channelSftp.lpwd());
			}
			// end lpwd
			else if (command.equals("get")) {
				try {
					if (params.length == 2) {
						channelSftp.get(params[1]);
					} else {
						channelSftp.get(params[1], params[2]);
					}
				} catch (SftpException e) {
					System.out.println("Ex)get centos.txt C:\\Users\\solulink");
				}
			}
			// end get
			else if (command.equals("put")) {
				String p1 = str.split(" ")[1];
				try {
					channelSftp.put(p1);
				} catch (SftpException e) {
					System.out.println("Ex)put window.txt");
				}
			}
			// end put
			else if (command.equals("ls") || command.equals("dir")) {
				String path = ".";
				try {
					Vector vector = channelSftp.ls(path);
					if (vector != null) {
						for (int i = 0; i < vector.size(); i++) {
							Object obj = vector.elementAt(i);
							if (obj instanceof ChannelSftp.LsEntry) {
								System.out.println(((ChannelSftp.LsEntry) obj).getLongname());
							}
						}
					}
				} catch (SftpException e) {
					System.out.println(e.toString());
				}
			}
			// end ls
			else if (command.equals("rm")) {
				try {
					String p1 = str.split(" ")[1];
					channelSftp.rm(p1);
				} catch (SftpException e) {
					System.out.println("Couldn't delete file: No such file or directory");
				}
			}
			// end rm
			else if (command.equals("mkdir")) {
				String p1 = str.split(" ")[1];
				try {
					channelSftp.mkdir(p1);
				} catch (SftpException e) {
					e.printStackTrace();
				}
			}
			// end mkdir
			else if (command.equals("rmdir")) {
				String p1 = str.split(" ")[1];
				try {
					channelSftp.rmdir(p1);
				} catch (SftpException e) {
					System.out.println("Couldn't remove diretory: No such file or directory");
				}
			}
			// end rmdir
			else if (command.equals("chmod")) {
				// 접근권한 설정
				// chmod 777 window.txt(rwx:7 x:1 wx:3 r-x:5)
				String p1 = str.split(" ")[1];
				String p2 = str.split(" ")[2];
				try {
					channelSftp.chmod(Integer.parseInt(p1), p2);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (SftpException e) {
					e.printStackTrace();
				}
			}
			// end chmod
			else if (command.equals("chown")) {
				String p1 = str.split(" ")[1];
				String p2 = str.split(" ")[2];
				try {
					channelSftp.chown(Integer.parseInt(p1), p2);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (SftpException e) {
					e.printStackTrace();
				}
			}
			// end chown
			else if (command.equals("ln") || (command.equals("symlink"))) {
				String p1 = str.split(" ")[1];
				String p2 = str.split(" ")[2];
				try {
					channelSftp.symlink(p1, p2);
				} catch (SftpException e) {
					e.printStackTrace();
				}
			}
			// end ln
			else if (command.equals("quit")) {
				channelSftp.quit();
				break;

			} else {
				System.out.println("Invalid command.");
			}
		}
		channelSftp.disconnect();
		// 스캐너자원반납
		scanner.close();
		// 시스템종료
		System.exit(0);
	}
}

7.구축된 java sftp client(window) 환경에서 sftp server(linux/ubuntu)로 접속 후 명령어 실행 결과.


8.sftp server os 정보 참고.

$ hostnamectl
...
	Operating System: Ubuntu 18.04.5 LTS
	Kernel: Linux 5.11.5
	Architecture: x86-64
...
728x90
728x90