0

我正在尝试使用 Jsch 将服务器上的文件从一个目录复制到另一个目录。我正在使用 SFTP 协议 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();
    } 

这是例外

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)
4

1 回答 1

2

您必须在一个通道中执行 get() 操作,并在另一个通道中执行 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();
    }
}
于 2014-09-05T13:16:30.613 回答