Java Ftp(透過跳板)

FTP透過跳板的概念與參考整理。

一般FTP 連線

1
Request --->  FTP Server

一般FTP 連線(透過跳板)

1
Request ---> Jump Server ---> FTP Server

實作參考(dependency: jsch)

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
private static Session getJschSession(String username, String password, String host, int port) {
try {
JSch jsch = new JSch();
Session jschSession = jsch.getSession(username, host);
jschSession.setPassword(password);
jschSession.setPort(port);
Properties sessionConfig = new Properties();
sessionConfig.put("StrictHostKeyChecking", "no");
jschSession.setConfig(sessionConfig);
return jschSession;
} catch (Exception e) {
log.error("Exception: {}", e);
}
return null;
}


public static void deployByJump(CustomProperties prop, List<CompileOrder> deployList) {
Date now = new Date();
String destPath = prop.getDestPath();
Session jumpSession = null;
Session sftpSession = null;
ChannelSftp ftp = null;
try {
// 先連線跳板
jumpSession = getJschSession(prop.getJumpUserId(), prop.getJumpPassword(), prop.getJumpServer(), 22);
jumpSession.connect();
int portForwarding = 2222;
jumpSession.setPortForwardingL(2222, prop.getFtpServer(), 22); // 在該台綁定一個port

// 透過這個port轉送
sftpSession = getJschSession(prop.getFtpUserId(), prop.getFtpPassword(), "localhost", portForwarding);
sftpSession.connect();

ftp = (ChannelSftp) sftpSession.openChannel("sftp");
ftp.connect();
ftp.cd(destPath); // destPath
log.info("ftp.pwd():{}", ftp.pwd());

} catch (Exception e) {
log.error("Exception: {}", e);
}finally {
if(sftpSession != null) {
jumpSession.disconnect();
log.info("sftp session close.");
}
if(ftp != null) {
ftp.quit();
log.info("ftp quit.");
}
if(jumpSession != null) {
jumpSession.disconnect();
log.info("jump session close.");
}
}
}



private static String dateFormatToString(Date date, String pattern) {
return new SimpleDateFormat(pattern).format(date);
}