Friday, June 15, 2012

HowTo Copy Files Using SSH Without Providing Login Prompts

The following example is a suggestion you may want to use in some cases. It shows how files can be copied over the network using ssh without providing an interactive login prompt.

SSH allows you to do a forced command using the "command" option. When you use this option you can disable scp and enforce every passed ssh command to be ignored.
On the server side where you want to retrieve the file from, add the following entry to the beginning of the SSH key in the
~/.ssh/authorized_keys2 file:

command="/bin/cat ~/<file_name>" ssh-dss ABBCCD33Nza...OpenSSH key

To copy now the file from the remote server, you can run the following command:

ssh <user>@<server> > <local_file>

Since /bin/cat is executed on the server side, the output has to be redirected to the local file.

Another approach is to replace /bin/cat with your own script that checks the passed SSH commands by reading the environment variable $SSH_ORIGINAL_COMMAND. For example:
  if [[ $SSH_ORIGINAL_COMMAND = "File1" ||
        $SSH_ORIGINAL_COMMAND = "File2" ]]
      /bin/cat $SSH_ORIGINAL_COMMAND
      echo "Invalid file name!"
      exit 1
So you replace /bin/cat with the script name in ~/.ssh/authorized_keys2, and run the following command to copy "File1":
ssh <user>@<server> File1 > <local_file>

To copy "File 2", run:

ssh <user>@<server> File2 > <local_file>

Every other passed parameter will return an error.

Note that this document comes without warranty of any kind. But every effort has been made to provide the information as accurate as possible. I welcome emails from any readers with comments, suggestions, and corrections at webmaster_at

                                                Copyright © 2012 LINUXHOWTO.IN

1 comment:

  1. It’s very informative and you are obviously very knowledgeable in this area. You have opened my eyes to varying views on this topic with interesting and solid content. Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written.