How to enable SSH Key based authentication - Passwordless SSH

How to SSH without Password into remote Linux Server is the question that every Engineer working on Linux might have come across.

Sometimes the Question we seek could be different like

  1. ssh command without password
  2. ssh to the remote server without password
  3. SSH without password from Shell Script
  4. SCP to a remote server without password From Shell Script
  5. Passwordless SSH and SCP between Linux servers. etc..

But the solution remains the same. Which is enabling Key Based Authentication between servers

SSH without Password Key Based Authentication

So, How to enable SSH Key based authentication (or) Passwordless SSH in 2 steps

Execute the following commands in the server from where you are going to log in to the other (or) initiate the SSH command.

For example, If you want to log in to mwiapp02 server from mwiapp01 as wlsusr user. You should perform the following steps in mwiapp01 as wlsusr


Step1: Create SSH key for your username (if not already created) using the following command

This Step is to create SSH Key for your user.  The Generated SSH Key file would be placed in Home Directory of the current user under .ssh directory

The Filename of this Key would be id_rsa

ssh-keygen -q -b 2048 -t rsa -N "" -C "creating SSH" -f ~/.ssh/id_rsa


Step2: Copy the key file to the remote server to which you would like to login 

Using this ssh-copy-id command you can actually copy the public key of your user ( Generated from the last command) to the remote server and it would be appended into the homedirectory/.ssh/authorized_keys file

You can optionally do the aforementioned step manually also. But ssh-copy-id is the easy and efficient way to do it

ssh-copy-id wlsusr@mwiapp02

Here is a quick Demo on how to do it.


SSH from Shell Script and Execute commands after Key Based Authentication Enabled

As we are now having Passwordless SSH enabled you can do SSH and SCP without being prompted for the password.

Here is a Sample Script which copy an another Script file which has to be executed on the remote Server using SCP and invokes it with SSH.


# Read the ServerNames from Properties file
for server in `cat`
        # Printing the ServerName
        echo "Processing ServerName "$server

        # SCP - copy the script file from Current Directory to Remote Server and Ignore Host Key Verification
        scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $server:/tmp/
        # Take Rest for 5 Seconds
        sleep 5

        # SSH to remote Server  and Execute a Command [ Invoke the Script ] and Ignore Host Key Verification
        ssh   -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $server "/tmp/" > EnableLogRotationLog/$server.process

Hope it helps

Rate this article [ratings]


Sarav AK