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);
}
'Web > 현업 경험' 카테고리의 다른 글
CKEDITOR 4와 BOOTSTRAP MODAL 함께시 INPUT DISABLED BUG 해결 방법 (0) | 2022.07.08 |
---|---|
자바 파일 이름 변경 하기 (0) | 2020.09.11 |
[Lucy XSS filter] 3번 클릭 만에 적용하기! - XSS방지, 방어, 네이버XSS (0) | 2019.04.05 |
Mybatis 와 ibatis 별 동적 태그 (0) | 2019.04.05 |
[Front] js/css 파일 캐시 방지 (0) | 2019.04.05 |