gpt4 book ai didi

java - 使用 Jsch 将远程服务器上的文件从一个目录复制到另一个目录

转载 作者:行者123 更新时间:2023-12-01 13:52:26 31 4
gpt4 key购买 nike

我正在尝试使用 Jsch 将服务器上的文件从一个目录复制到另一个目录。我正在使用 SFTP 协议(protocol) put 和 get 方法来完成此任务。我这样做是因为我没有对服务器的 shell 访问权限。下面是我的代码示例和我收到的异常。有人可以告诉我如何解决这个问题吗?

OutputStream outputStream = null;
InputStream inputStream = null;
try
{
JSch jsch = new JSch();
session = jsch.getSession(USER,HOST,PORT);
session.setPassword(PASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications", "password");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
inputStream = channelSftp.get(fromFilename);
channelSftp.put(inputStream,toFilename);
} catch(Exception e){
e.printStackTrace();
} finally {
if(inputStream != null)
inputStream.close();
if(outputStream != null)
outputStream.close();
channelSftp.exit();
channel.disconnect();
session.disconnect();
}

这是一个异常(exception)

4: java.io.IOException: error: 4: RequestQueue: unknown request id 12
at com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:689)
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:540)
at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:492)

最佳答案

您必须在一个 channel 中执行 get() 操作,并在另一个 channel 中执行 put() 操作。这样可行。这是我的代码。

 public void cp (Session session, String source, String target) throws Exception {
log.info("COMMAND: cp " + source + " " + target);

if (!session.isConnected()) {
log.error("Session is not connected");
throw new Exception("Session is not connected...");
}
Channel upChannel = null;
Channel downChannel = null;
ChannelSftp uploadChannel = null;
ChannelSftp downloadChannel = null;
try {
upChannel = session.openChannel("sftp");
downChannel = session.openChannel("sftp");
upChannel.connect();
downChannel.connect();
uploadChannel = (ChannelSftp) upChannel;
downloadChannel = (ChannelSftp) downChannel;
FileProgressMonitor monitor = new FileProgressMonitor();
InputStream inputStream = uploadChannel.get(source);

downloadChannel.put(inputStream, target, monitor);
} catch (JSchException e) {
log.error("Auth failure", e);
throw new Exception(e);
} finally {
if (upChannel == null || downChannel == null) {
System.out.println("Channel is null ...");
}else if (uploadChannel != null && !uploadChannel.isClosed()){
uploadChannel.exit();
downloadChannel.exit();
uploadChannel.disconnect();
downloadChannel.disconnect();
}else if (!upChannel.isClosed()) {
upChannel.disconnect();
downChannel.disconnect();
}
session.disconnect();
}
}

关于java - 使用 Jsch 将远程服务器上的文件从一个目录复制到另一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19869446/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com