Monday, July 20, 2015

Generate and Using SSH Key


An SSH key allows you to login to a server from another computer without a password. This is useful when we access the remote server frequently and want to be automatically authenticated through SSH.
Two basic steps:
1. Generate an SSH key on your computer.
2. Copy the generated SSH key on the target Server. 
The target server authenticates any incoming SSH request using the key provided in SSH request.
Following explains how to generate and use SSH Key :

To generate a ssh file run the following command :

ssh-keygen -t rsa -C <<key name>>

i.e.
bash-3.2$ ssh-keygen -t rsa -C "testsshprofile"

The above will als ask for a passphrase, which is optional, but provids additional security to your ssh file by encrypting it and putting it in a restricted directory. If you provide a passphrase you will have to enter it every time you use SSH to connect to target server.



// The above will generate private and public files i.e. testsshprofile and testsshprofile.pub

  • testsshprofile :  Its the private key file and should not be shared. Anyone with this file can access the sever.  Here is the sample contents of the testsshprofile:

  • testsshprofile.pub : this is the public key file that is shared with the remote server, so it can recognize your machine. The contents of this file needs to be copied on target server in ssh configuration. Here is the sample contents of the testsshprofile.ssh:


Copy the SSH key on Remote Server:

Once the ssh files are generated we need to copy over the ssh file on target server. I assume you have the access to the target server and have required permission to edit ssh configs.

You can use the following command to append the public key on server

cat ~/.ssh/testsshprofile.pub | ssh user@hostname 'cat >> .ssh/authorized_keys'

You can also edit this file manually if you have access to the target server and you are trying to provide access to this server to some other users.

1. On your target server go to the ssh directory, you should see authorized_keys file in ssh directory.
>>  cd ~/.ssh

authorization  authorized_keys  id_rsa  id_rsa.pub  known_hosts

>> Edit the authorized_keys file and append the contents of the your public key (i.e. "testsshprofile.pub") in this file.

2. Restart the ssh service :

>> sudo /etc/init.d/sshd restart

// For Ubuntu
>> sudo service ssh restart

// CentOS
>> sudo service sshd restart

Connecting to the Server :

Once we have generated the SSH key and copied the ssh file over to target server, we can use the following command to access the remote server.

>> ssh -i <<path to public key>> user@<<IP address>>

i.e.  ssh -i /test/location/testsshprofile.pub devuser@10.1.20.129

Make sure your ssh file has the correct permission or else you might get authentication error.

>> chmod 600 testsshprofile


No comments:

Post a Comment