JSch SCP file transfer using “exec” channel

2020-02-13 02:50发布

问题:

I'm very new to the SCP protocol and JSch. I have to transfer a file fro a remote device via SCP to Android. The server side developers refused to tell be anything about their device except for the file location, and the root account which can be used to access it with SCP.

Here are the steps I tried.

  1. Confirm that using JSch, my Android client can establish connection with the server. [complete]

  2. Confirm that using JSch, and the ChannelExec object, I can send the ls command and read its output. [complete]

  3. Confirm that using JSch, and the ChannelSFTP object, I can transfer a file from the device. [failed]

The reason why (3) failed seems that the device (server) is not configured for SFTP. The maker keeps on saying that commands on ssh like below works:

scp root@192.168.5.1/usr/WS026.jpeg [targetPath]

They say that the above command will copy the first parameter to the target path of the client. So, alternative to using the SFTP, how can I implement that in JSch channel "exec"?

回答1:

If the device supports SCP only, do not try to use SFTP, use SCP.

There's an official example for implementing the SCP download using the JSch:
http://www.jcraft.com/jsch/examples/ScpFrom.java.html


Do not get confused by the call of scp in the example code. That's how SCP protocol works. A local (OpenSSH) scp executes the scp on the remote server (with specific non-public arguments, in this case the -f) and then the two instances talk to each other. The example implements the local scp. The arguments used for the remote scp are not the arguments you would use for the local scp.

See also Explanation for SCP protocol implementation in JSch library.