Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- 주식 청약 일정
- IPO
- 6월 공모주 청약 일정
- SQL
- 공모주 청약
- 공모주 청약 일정
- JavaScript
- 제이쿼리
- 공모주
- 리눅스
- Eclipse
- 주식
- jquery
- 오라클
- 7월 공모주 청약 일정
- java
- Stock
- linux
- html
- 자바
- MYSQL
- 주식 청약
- 코드이그나이터
- php
- Stock ipo
- css
- codeigniter
- 맥
- Oracle
- 자바스크립트
Archives
- Today
- Total
개발자의 끄적끄적
[java] 자바(java)로 만든 FTP와 SFTP Client 통합 프로그램 [펌] 본문
728x90
반응형
[java] 자바(java)로 만든 FTP와 SFTP Client 통합 프로그램 [펌]
아래에는 FTP, SFTP 따로 동작하는 프로그램인데
클래스를 크게 3개로 나누어서 통합프로그램을 만들었습니다.

서버로 설정한 CentOS
Virtual Box를 사용하여 CentOS를 임의의 서버로 설정하였습니다.

프로젝트 구조
프로젝트 구조는 위 사진과 같습니다.
FTP와 SFTP를 사용하기 위해선 commons.net과 JSch라이브러리가 필요한데 이와 관련된 내용은 아래글에 있고,
여기선 통합프로그램을 어떻게 구현했는지에 대한 코드만 올리겠습니다.
ProgramStart.java
package program;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class ProgramStart {public static void main(String[] args) {// 메인 메소드String command = "";BufferedReader br = new BufferedReader(new InputStreamReader(System.in));MyFTPClient myFTPClient = new MyFTPClient();MySFTPClient mySFTPClinet = new MySFTPClient();System.out.print("프로토콜 유형: ");try {command = br.readLine();if (command.equals("ftp") || command.equals("FTP")) {myFTPClient.start();} else if (command.equals("sftp") || command.equals("SFTP")) {mySFTPClinet.start();} else {System.out.println("어떤 프로토콜을 쓸건지 다시 입력해주세요.");System.exit(0);}} catch (IOException e) {e.printStackTrace();}}}
MyFTPClient.java
package program;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Scanner;import org.apache.commons.net.ftp.FTP;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;public class MyFTPClient {public void start() {FTPClient ftpClient = new FTPClient();// 서버접속Scanner scanner = new Scanner(System.in);System.out.print("호스트 주소 입력: ");String server = scanner.nextLine();try {ftpClient.connect(server, 21);if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {System.out.println(server + "에 연결됐습니다.");System.out.println(ftpClient.getReplyCode() + " SUCCESS CONNECTION.");}} catch (Exception e) {System.out.println("서버 연결 실패");System.exit(0);}// 계정입력System.out.print("계정 입력: ");String user = scanner.nextLine();System.out.print("비밀번호 입력: ");String password = scanner.nextLine();try {ftpClient.login(user, password);System.out.println(ftpClient.getReplyCode() + " Login successful.");} catch (IOException e) {System.out.println(ftpClient.getReplyCode() + " Login incorrect.");System.exit(0);}// 명령어시작while (true) {System.out.print("ftp> ");String str = "";str = scanner.nextLine();String[] params = str.split(" ");String command = params[0];// 명령어 시작if (command.equals("cd")) {String path = params[1];try {ftpClient.changeWorkingDirectory(path);} catch (IOException e) {e.printStackTrace();}} // end cdelse if (command.equals("mkdir")) {String directory = params[1];try {ftpClient.makeDirectory(directory);} catch (IOException e) {e.printStackTrace();}} // end mkdirelse if (command.equals("rmdir")) {String directory = params[1];try {ftpClient.removeDirectory(directory);} catch (IOException e) {e.printStackTrace();}} // end rmdirelse if (command.equals("binary")) {try {ftpClient.setFileType(FTP.BINARY_FILE_TYPE);System.out.println(ftpClient.getReplyCode() + " Switching to Binary mode.");} catch (IOException e) {e.printStackTrace();}} // end binaryelse if (command.equals("ascii")) {try {ftpClient.setFileType(FTP.ASCII_FILE_TYPE);System.out.println(ftpClient.getReplyCode() + " Switching to ASCII mode.");} catch (IOException e) {e.printStackTrace();}} // end asciielse if (command.equals("pwd")) {try {System.out.println(ftpClient.printWorkingDirectory());} catch (IOException e) {e.printStackTrace();}} // end pwdelse if (command.equals("quit")) {try {ftpClient.logout();System.out.println(ftpClient.getReplyCode() + " Goodbye.");break;} catch (IOException e) {e.printStackTrace();}} // end quitelse if (command.equals("put")) {String p1 = str.split(" ")[1];String p2 = str.split(" ")[2];File putFile = new File(p2);InputStream inputStream = null;try {inputStream = new FileInputStream(putFile);boolean result = ftpClient.storeFile(p1, inputStream);if (result == true) {System.out.println("업로드 성공");} else {System.out.println("업로드 실패");}} catch (IOException e) {e.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}} // end putelse if (command.equals("get")) {String p1 = str.split(" ")[1];String p2 = str.split(" ")[2];File getFile = new File(p2);OutputStream outputStream = null;try {outputStream = new FileOutputStream(getFile);boolean result = ftpClient.retrieveFile(p1, outputStream);if (result == true) {System.out.println("다운로드 성공");} else {System.out.println("다운로드 실패");}} catch (FileNotFoundException e1) {e1.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}} // end getelse if (command.equals("delete")) {String file = str.split(" ")[1];try {ftpClient.deleteFile(file);} catch (IOException e) {e.printStackTrace();}} // end rmelse if (command.equals("ls")) {String[] files = null;try {files = ftpClient.listNames();for (int i = 0; i < files.length; i++) {System.out.println(files[i]);}} catch (IOException e) {e.printStackTrace();}} // end lselse if (command.equals("dir")) {FTPFile[] files = null;try {files = ftpClient.listFiles();for (int i = 0; i < files.length; i++) {System.out.println(files[i]);}} catch (IOException e) {e.printStackTrace();}} // end dir} // end whiletry {ftpClient.disconnect();} catch (IOException e) {e.printStackTrace();} finally {scanner.close();}System.exit(0);}}
MySFTPClient.java
package program;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 MySFTPClient {public void start() {// https://lahuman.jabsiri.co.kr/152// DH알고리즘을 쓰기위한 코드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 cdelse if (command.equals("lcd")) {// lcd C:\Users\solulinkString 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 lcdelse if (command.equals("pwd")) {try {System.out.println("Remote working directory: " + channelSftp.pwd());} catch (SftpException e) {e.printStackTrace();}} // end pwdelse if (command.equals("lpwd")) {// lpwdSystem.out.println("Local working directory: " + channelSftp.lpwd());} // end lpwdelse 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 getelse if (command.equals("put")) {String p1 = str.split(" ")[1];try {channelSftp.put(p1);} catch (SftpException e) {System.out.println("Ex)put window.txt");}} // end putelse 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 lselse 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 rmelse if (command.equals("mkdir")) {String p1 = str.split(" ")[1];try {channelSftp.mkdir(p1);} catch (SftpException e) {e.printStackTrace();}} // end mkdirelse 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 rmdirelse 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 chmodelse if (command.equals("chown")) {// 파일소유권변경->일반계정에 root권한 부여(vi /etc/passwd->UID와GID변경)// 리눅스에서 cat /etc/passwd// jinpyolee : 1000 sftpuser : 1004// chown 1000 window.txtString 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 chownelse if (command.equals("ln") || (command.equals("symlink"))) {// 링크파일 생성(rwxrwxrwx, 리눅스에서 하늘색으로 나옴)// ln window.txt win.txtString p1 = str.split(" ")[1];String p2 = str.split(" ")[2];try {channelSftp.symlink(p1, p2);} catch (SftpException e) {e.printStackTrace();}} // end lnelse if (command.equals("quit")) {channelSftp.quit();// 반복문 나가서 종료break;} // end quitelse {System.out.println("Invalid command.");}} // end while// 연결해제channelSftp.disconnect();// 스캐너자원반납scanner.close();// 시스템종료System.exit(0);}}// end class
메인은 ProgramStart.java에 있습니다.

FTP로 서버에 접속한 모습
FTP를 이용해 서버(CentOS)에 접속한 모습입니다.
구현된 명령어 사용은 생략하겠습니다.

SFTP로 서버에 접속한 모습
SFTP를 이용해 서버에 접속한 모습입니다.
연결 순서가 조금 다르긴하나 큰 차이는 없습니다.
연결후 CMD창에서와 같이 명령어를 사용하면 됩니다.
출처: https://thefif19wlsvy.tistory.com/5 [FIF's 코딩팩토리]
반응형
'개발 > java & jsp' 카테고리의 다른 글
| [java] SFTP 사용방법 (jsch 라이브러리 사용) (0) | 2020.02.29 |
|---|---|
| [java] 리스트돌릴땐 무조건 foreach를 사용하자 [펌] (0) | 2020.02.29 |
| [java] [Eclipse]java프로젝트에 jar파일 추가하기, jar파일 상대경로로 넣기 [펌] (0) | 2020.02.27 |
| [java] eclipse Could not create the Java virtual machine 에러 해결방법 (0) | 2020.02.25 |
| [java] 자바(java)에서 SAP 연계하여 데이터 조회 [펌] (0) | 2020.02.06 |
Comments
