I am contemplating over an example of JSch library usage which can be found here:
http://www.jcraft.com/jsch/examples/ScpFrom.java.html
I cannot understand several code patterns from this example. Here they are:
Is there any reasons to prefer SCP over SFTP, which can be ran using the same library?
Why we run
scp -f <remote file>
on remote host instead of running simplyscp source_file_path destination_file_path
? Why execution on remote host is better?In the beginning of the transfer there is a line
while(true){ int c=checkAck(in); if(c!='C'){ break; } ...
what is the meaning of this magical
C
letter? WhyC
?Why to send this signal all the time?
// send '\0' buf[0]=0; out.write(buf, 0, 1); out.flush();
how this can read filesize?
long filesize=0L; while(true){ if(in.read(buf, 0, 1)<0){ // error break; } if(buf[0]==' ')break; filesize=filesize*10L+(long)(buf[0]-'0'); //What is this?? }
No, the SCP protocol is obsolete. You should always use SFTP nowadays.
Though trivial implementations of the SFTP protocol tend to have slower transfers than SCP (it's not easy to implement the SFTP transfer efficiently due to its packet nature).
It's how SCP protocol works. The OpenSSH
scp
binary works both as a server and a client. So when you runscp
locally, it connects over SSH and runsscp
on the server. Then the two instances communicate with each other. The JSch replaces the local instance of thescp
. But it still needs the remote instance to complete the transfer.If you were running
scp
locally, you would have to have OpenSSH installed on the machine. What is maybe common on Unix, but definitely not on Windows. Also there's no easy/standardized way to capture results from thescp
program, to translate them to JSch Java interface. It's the same reason why JSch (or any other SFTP library) implements SFTP protocol on its own, instead of usingsftp
program.Every command of the SCP protocol is identified by a single character. The
C
stands for "file transfer",D
stands for "directory transfer",T
before file transfer indicates modification time of the next transferred file, etc. I do not know why it'sC
and not for exampleF
.The NULL (
\0
) character command is confirmation/response to the other site that the received command was completed.The
C
command has syntax (it's a human-readable string):For example:
The loop in the code translates the string
"153634"
to a number 153634. It looks like a bit too complicated implementation, but it works.