2011-11-03 26 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

相關問題