Sunday, November 11, 2012

Transferring file over SSH without SCP or SFTP

This post is not directly related to programming as this blog was meant to be. However, it may be useful in developer's everyday life, especially when working with mobile or embedded devices.

Imagine you have a machine which is connected to a network, but you do not have any service for transferring files - the only thing you can do is to plug an USB stick to the port. You also have a basic SSH server which SCP refuses to cooperate with (or you might have built Dropbear server for the machine with basic functionality).

We do not have any application for transferring data, but we do have access to the shell. If thought for some time, there is a tiny shell command which can prove its power and utility here - the command for simply copying, byte-by-byte, data from standard input to standard output - namely, the cat command.

One of the features of standard SSH client command available in most distribution of Linux is the possibility of invoking, just after establishing a connection, any command - instead of a standard shell. Just like with standard shell, client's standard input will be transferred over SSH connection to the server and similarly the standard output will get back to client.

You might have already caught the point, if also realized that we can redirect standard input and output to files using standard operators of shell - < and >.

At the server, we want to put the incoming data to the file, thus our command will look like the following:
cat > ~/file_to_save_to

At the client, on the other hand, we want to get the given file to transfer:
cat < ~/file_to_read_from

Putting all together, we finally come up with the following:
< ./source_file cat | ssh server "cat > ./target_file"

The invocation line above also makes use of not widely known feature of bash shell that the redirection operators may not only be after a command but can also precess it.

No comments:

Post a Comment