Monday, 8 September 2014

How to generate SSH keys and use it for Sftp / SSH/ SCP?

How to generate SSH keys and use it for Sftp / SSH/ SCP?

SSH keys are commonly used during sftp and scp to authourize access to a host machine. Instead of using a password, ssh keys are used to identify and authourize a machine to login to a target machine. It is more safe and hard to breakin.

In brief, the steps to set up ssh authetication would be as follows:

Step a: On any source/client machine, use the command below to generate the ssk keys:

ssh-keygen -t rsa -f <nameofthekeyfile>

Example: ssh-keygen -t rsa -f mykeys-for-targetmachine

The command will prompt for keys size, expiry date, passphase, etc. You can enter the values you deem fit for your purpose.The above command will create a private and pub key with the key name mykeys-for-targetmachine you have provided in the command. The public key file will have .pub extention.

Step b: Now open the public key file and copy the contents of the key file.


The output will look something like this:

Step c: Login to the target machine that you want to access and open the authorised_keys file. This file should be in your home directory.Paste the contents of the public file that you copied in step b to this file.

Step d: Back to the source/client machine, change the permission of the keys to make it secure.
For the above example, it would be:

chmod 600 mykeys-for-targetmachine

Step e: Now try to SSH to target machine using your new keys to test the connection: The command would be something like the below (replace the <myuser> with the user name requierd on the target machine and the <targetmachine> with the name of the target machine that you want to login i.e. the machine to with the authourized key file that you just updated in step c:

ssh -i mykeys-for-targetmachine <myuser>@<targetmachine>

it will prompt first to add the target machine to the list of known host, press yes and you should be now logged into the machine. If it prompts for a password then you haven't done something right. Check the above steps and do the required correction.

How to sftp and scp using ssh keys? Below are the commands to use:

sftp -i mykeys-for-targetmachine <myuser>@<targetmachine>
scp -i  mykeys-for-targetmachine <myuser>@<targetmachine>

More information can be found in the below link: