我正在使用Jsch 0.1.44
将文件从一个主机scp到另一个主机。相关代码如下:
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
出现此错误的原因是什么?我怎么能避免呢?
非常感谢任何帮助。
答案 0 :(得分:2)
我找到了解决方案。看来命令中的源文件名不能包含任何斜杠。要解决这个问题,您只需更改此行:
command+=file;
进入这个:
command+=file.getName();
多数民众赞成。