【发布时间】:2020-10-11 08:48:05
【问题描述】:
我想使用 JSch 或脚本通过 Java 中的 SFTP 将文件从存储桶 GCP 传输到远程服务器,而不是我的本地目录。
try{
JSch jsch = new JSch();
jsch.addIdentity(privateSftpKey);
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
log.info("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
log.info("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
String sftpDirectory = "/home/share";
File directory = new File("C:\\Users\\XYZ\\Desktop\\Learning\\Projects\\TransferStorageBucketToRemoteServer");
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
String filename=file.getAbsolutePath();
channelSftp.put(filename, sftpDirectory, ChannelSftp.OVERWRITE);
System.out.println(filename + " transferred to " + sftpDirectory );
}
}
log.info("File transfered successfully to host.");
} catch (Exception ex) {
log.info("Exception found while tranfer the response.");
log.info("Exception Message...: {}",ex.getMessage());
}
当我在互联网上搜索时,只有从
- 存储桶到另一个存储桶或
- 存储桶到本地目录,反之亦然
谷歌云存储API代码,从存储桶读取文件
Credentials credentials = GoogleCredentials
.fromStream(new FileInputStream(jsonKey));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials)
.setProjectId("projectId").build().getService();
Blob blob = storage.get("bucket-name", "file.txt");
ReadChannel readChannel = blob.reader();
但不确定如何直接从 GCP ReadChannel 将其上传到 SFTP 通道而不将其写入另一个输出文件,然后将其传输到 SFTP 通道
channelSftp.put(file_from_readChannel , sftpDirectory, ChannelSftp.OVERWRITE);
但我看不到从存储桶直接传输到远程服务器。
任何人都可以在这方面提供帮助,以及在 java 或命令中的可能方式吗?
【问题讨论】:
-
你有什么问题?您不能直接从 GCS 传输到 SFTP。您必须编写一些代码,例如您的代码,但不能使用 File API,而必须使用 Google Cloud Storage API,仅此而已。
-
谢谢@guillaumeblaquiere 我已经尝试过存储API,但卡在了channelSftp.put(file_from_readChannel, sftpDirectory, ChannelSftp.OVERWRITE);我已经编辑并添加了上面有问题的代码以供参考。
-
GCS 和 SFTP 之间没有直接通信。字节(至少在流中)必须像代理一样通过您的应用程序。流式读取会阻止您在本地存储文件,但不会执行校验和。
-
这段java代码在哪里运行?如果它在您可以访问操作系统的环境中运行,您可以使用 gcsfuse 挂载存储桶并将其作为本地文件传输到远程 sftp。
-
@JoséSoní 我的应用程序将在 Kubernetes 中运行,我需要每天将文件从 Kubernetes(存储桶或一些独立于运行的 pod 的存储)传输到远程服务器。
标签: google-cloud-platform sftp jsch