【发布时间】:2018-04-24 14:48:03
【问题描述】:
有一个用例,我必须:
- 在应用程序服务器上的应用程序中生成文件。让我们称这台机器为 A*。 (这是我的 Java 代码运行的地方,用于生成文件)
- 从应用程序本身,我希望使用 SFTP 将此文件传输到白名单服务器B,以固定路径(例如
/home/fixed/file.xlsx)李>
第 1 点和第 2 点是直截了当的。
现在有一个外部服务器C(我提供了它的凭据)
- 现在,应用程序正在服务器 A 上运行。
- 文件现在位于 Server B 中 ==>
/home/fixed/file.xlsx。 - 我必须通过 SFTP 将文件从 Server B 传输到 Server C。
如何实现这种多跳 SFTP 传输?
(B上不需要文件,一旦成功发送到C)
编辑:Martin Prikryl 的回答帮助我实现了这一目标。
@Override
public void createOurChannel(Path lastModifiedBankFile) {
LOG.info("Initiating SFTP for white-listed Server B for file: {}",
lastModifiedBankFile);
String host = properties.getServerBSftpHost();
String port = properties.getServerBSftpPort();
String password = properties.getServerBSftpPassword();
String username = properties.getServerBSftpUsername();
Session session = null;
try {
JSch ssh = new JSch();
JSch.setConfig("StrictHostKeyChecking", "no");
session = ssh.getSession(username, host, Integer.parseInt(port));
session.setPassword(password);
session.connect();
this.sendFileToBank(lastModifiedBankFile, session, ssh);
} catch (JSchException e) {
LOG.error("Jsch Exception occurred while SFTP.", e);
} finally {
if (session != null && session.isConnected())
session.disconnect();
LOG.info("Successfully disconnected from SFTP. {}");
}
}
@Override
public void sendFileToBank(Path lastModifiedBankFile, Session session, JSch ssh) {
Session sessionBank = null;
Channel channelBank = null;
ChannelSftp channelSftp = null;
String host = properties.getBankSftpHost();
String port = properties.getBankSftpPort();
String password = properties.getBankSftpPassword();
String username = properties.getBankSftpUsername();
String bankSftpDir = properties.getBankSftpEmiDir();
try {
int portForwarded = 2222;
session.setPortForwardingL(portForwarded, host, Integer.parseInt(port));
sessionBank = ssh.getSession(username, "localhost", portForwarded);
sessionBank.setPassword(password);
sessionBank.connect();
channelBank = sessionBank.openChannel("sftp");
channelBank.connect();
channelSftp = (ChannelSftp) channelBank;
channelSftp.put(lastModifiedBankFile.toAbsolutePath().toString(),
bankSftpDir + lastModifiedBankFile.getFileName().toString());
channelSftp.exit();
} catch (JSchException e) {
LOG.error("Jsch Exception occurred while SFTP.", e);
} catch (SftpException e) {
LOG.error("SFTP Exception occurred while SFTP.", e);
} finally {
if (channelBank != null && channelBank.isConnected())
channelBank.disconnect();
if (sessionBank != null && sessionBank.isConnected())
sessionBank.disconnect();
}
}
【问题讨论】:
标签: java ssh spring-integration sftp spring-integration-sftp