2011-11-03 134 views
1

我使用Jsch 0.1.44 scp从一个主机到另一个文件的文件。相关的代码如下:在此行带jsch的scp文件给出'意想不到的文件名'

out.write(command.getBytes()); 

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

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

看起来像这样的命令C0644 5878 /home/myuser/config.xml

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

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

任何帮助,高度赞赏。

+0

该命令是否需要'scp/path/to/local/file server:path/to/remote/file'?我不知道'-t'选项的作用。 – trojanfoe

+0

scp -t执行远程复制命令。我从jsch的例子中拿走了它。 – flash

回答

2

我找到了解决方案。看起来命令中的源文件名不能包含任何斜线。为了解决这个问题,你简单的需要更改此行:

command+=file; 

到这一点:

command+=file.getName(); 

完蛋了。

+2

嘿 - 我使用sharpssh这是这个库的.net端口,我得到同样的错误。我对您的解决方案有疑问 - 如果您不能在名称中加入斜线,您如何为目的地提供不同的路径? – Karl

+0

@Karl的路径在这里并不重要。看看你如何在上面我最初的问题中改变路径。 destDirectory就是您要查找的内容。 – flash

+0

啊我明白了,有道理。感谢您指出了这一点。 – Karl

相关问题