问题
I'm using Jsch 0.1.44
to scp a file from one host to another. The relevant code is the following:
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;
}
The command in this line
((ChannelExec)channel).setCommand(command);
looks like this: scp -t /tmp/config.xml
and the command in this line
out.write(command.getBytes());
looks like this: C0644 5878 /home/myuser/config.xml
The problem is, that I get the following error from scp: scp: error: unexpected filename: /path/to/config.xml
What is the reason for this error? How can I avoid it?
Any help is highly appreciated.
回答1:
I've found a solution. It seems that the source filename in the command must not contain any slashes. To solve this problem you simple have to change this line:
command+=file;
into this:
command+=file.getName();
Thats it.
来源:https://stackoverflow.com/questions/7991794/scp-file-with-jsch-gives-unexpected-filename