Set passwordless SSH for linux servers using private/public keys

This post will describe how to set passwordless SSH access on a linux server for a particular user.

Login to linux server with a username and password first. Generate SSH key for this user using below command,

ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa

Above command will generate 2 files in ~/.ssh/ directory. (1)id_rsa and (2) ~/.ssh directory is for current logged in user. -P option is to password protect your SSH key. In this case I am keeping a blank password(-P “”). -f option specifies file path to generate SSH key files. id_rsa is private key file that you should save on other client from where you want to SSH into server. file is public key file that should be appended or copied in ~/.ssh/authorized_keys file on linux server. Idea is that only id_rsa private key can unlock public key when user logs in using this private key.

To copy/append key file content to authorized_keys file, run below command on linux server.

cat ~/.ssh/ >> ~/.ssh/authorized_keys
//Below command is necessary to set correct permissions on authorized_keys file
chmod 0600 ~/.ssh/authorized_keys

Same public key can also be copied to other linux servers that has same user. This will allow that user to login to both servers using same private key file. Run below command to copy same public key on other servers.

ssh-copy-id -i $HOME/.ssh/ user@other-server-ip

Above command will prompt you one time for password of other server. This is just so that it can copy file on other server.

Once public key is copied to authorized_keys file, you can test SSH login on a client machine using id_rsa private key file. It should not prompt you for password.

ssh user@server-ip -i ~/.ssh/id_rsa

-i option is to specify private key file. If client machine is also a linux server and has same user as other server then you don’t even need to specify -i option. It will automatically pick id_rsa file from your ~/.ssh directory and login. This is useful for automated installs like Cloudera or Hortonworks hadoop platforms.

ssh user@server-ip

Above command should log you in without askig password.

Leave a Reply

Your email address will not be published. Required fields are marked *