Web/현업 경험
JSCH 라이브러리를 사용해서 SFTP / SSH 클라이언트 구현하기
꿈풀이
2020. 8. 21. 14:08
SFTP 클라이언트 구현하기
- SFTP 접속하기 예제
private void connect() {
System.out.println("==> Connecting to " + host);
Session session = null;
Channel channel = null;
// 1. JSch 객체를 생성한다.
JSch jsch = new JSch();
try {
// 2. 세션 객체를 생성한다(사용자 이름, 접속할 호스트, 포트를 인자로 전달한다.)
session = jsch.getSession(username, host, port);
// 3. 패스워드를 설정한다.
session.setPassword(password);
// 4. 세션과 관련된 정보를 설정한다.
java.util.Properties config = new java.util.Properties();
// 4-1. 호스트 정보를 검사하지 않는다.
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// 5. 접속한다.
session.connect();
// 6. sftp 채널을 연다.
channel = session.openChannel("sftp");
// 7. 채널에 연결한다.
channel.connect();
} catch (JSchException e) {
e.printStackTrace();
}
// 8. 채널을 FTP용 채널 객체로 캐스팅한다.
channelSftp = (ChannelSftp) channel;
System.out.println("==> Connected to " + host);
}
- SFTP 업로드하기 예제
public void upload(String catalinaHome, File file) throws SocketException, IOException {
// 앞서 만든 접속 메서드를 사용해 접속한다.
connect();
System.out.println("==> Uploading: " + file.getPath() + " at " + host);
FileInputStream in = null;
try {
// 입력 파일을 가져온다.
in = new FileInputStream(file);
// 업로드하려는 위치르 디렉토리를 변경한다.
channelSftp.cd(catalinaHome + "/webapps");
// 파일을 업로드한다.
channelSftp.put(in, file.getName());
} catch (SftpException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
// 업로드된 파일을 닫는다.
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("==> Uploaded: " + file.getPath() + " at " + host);
}