【问题标题】:Scp file with jsch gives 'unexpected filename'带有 jsch 的 Scp 文件给出“意外的文件名”
【发布时间】:2011-12-20 23:09:17
【问题描述】:

我正在使用Jsch 0.1.44 将文件从一台主机发送到另一台主机。相关代码如下:

public boolean transferFileToHost(File fileToTransfer, String destDirectory, String destFilename) {
    Channel channel = null;
    try {
        String command = "scp -t "+ destDirectory + destFilename;
        channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);

        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();

        if(!connectToChannel(channel, in)) {
            return false; 
        }

        if(!sendScpCommand(fileToTransfer, command, out, in)) {
            return false;
        }

        if(!sendFileContent(out, fileToTransfer, in)) {
            return false;
        }

        return true;
    } catch (IOException e) {
        logger.error("Error while reading file. Error was: ",e);
    } catch (JSchException e) {
        logger.error("Error while sending ssh commands. Error was: ",e);
    } 
    finally {
        if(channel != null) {
            channel.disconnect();
        }
    }

private boolean sendScpCommand(File file, String command, OutputStream out, InputStream in) throws IOException {
    long filesize=file.length();
    command="C0644 "+filesize+" ";
    command+=file;
    command+="\n";

    out.write(command.getBytes());
    out.flush();
    if (checkAck(in) != 0) {
        return false;
    }
    return true;
}

这一行的命令

((ChannelExec)channel).setCommand(command);

看起来像这样:scp -t /tmp/config.xml 和这一行中的命令

out.write(command.getBytes());

看起来像这样:C0644 5878 /home/myuser/config.xml

问题是,我从 scp 收到以下错误:scp: error: unexpected filename: /path/to/config.xml

这个错误的原因是什么?我怎样才能避免它?

非常感谢任何帮助。

【问题讨论】:

  • 命令不是必须是scp /path/to/local/file server:path/to/remote/file吗?我不知道-t 选项的作用。
  • scp -t 执行远程复制命令。我从 jsch 示例中获取了它。

标签: java scp jsch


【解决方案1】:

我找到了解决方案。似乎命令中的源文件名不能包含任何斜杠。要解决此问题,您只需更改此行:

command+=file;

进入这个:

command+=file.getName();

就是这样。

【讨论】:

  • 嘿 - 我使用的是这个库的 .net 端口的 sharpssh,我得到了同样的错误。我对您的解决方案有疑问 - 如果您不能在名称中添加斜杠,您如何为目的地提供不同的路径?
  • @Karl 路径在这里无关紧要。在我上面的初始问题中查看如何更改路径。 destDirectory 就是您要查找的目录。
  • 我迷路了。有人可以在婴儿中解释问题和解决方案是什么吗?我正在使用 SSH.NET(SharpSSH 的改造)。
猜你喜欢
  • 2015-06-06
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 2014-05-08
  • 2014-08-18
  • 2017-02-25
  • 1970-01-01
相关资源
最近更新 更多