1

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

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

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

非常感谢任何帮助。

4

1 回答 1

2

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

command+=file;

进入这个:

command+=file.getName();

就是这样。

于 2011-11-03T09:10:33.113 回答