For SSH, Keybased authentication is often suggested rather than password based authentication, since most passwords, if not complex enough, can be compromised by persistent attackers.
Keybased ssh authentication will allow you to login to a server without password. This will help you from the hustle of storing/remembering your user passwords. See our tutorial for creating users, if you still haven't created a user on your server.
How does it work?
In short this is what happens.
We are going to create a key pair(public/private) in our local computer. We shall then upload this public key pair to our server. Now, whenever our local computer authenticates with the server, public key in the server and private key in our local computer will match and authentication will succeed.
You can generate an SSH keypair using the command
In your local computer, execute the below command.
-$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/localuser/.ssh/id_rsa):
You will then be asked where to store the private key. Default location is within
.ssh directory under corresponding users home directory. Press enter if you don't want to change the default location.
Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /localuser/.ssh/id_rsa. Your public key has been saved in /localuser/.ssh/id_rsa.pub.
You will then be asked for a passphrase. Passphrase add's an additional layer of security. If you don't wish to use a passphrase, press enter.
You have now created public/private key pair in your computer. If you have chosen the default locations for storing public/private key,
- Private key will be in
- Public key will be in
Copy public key to server
You can execute the below command in your local computer to copy public to the server.
cat ~/.ssh/id_rsa.pub | ssh user@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
This will copy your public key to the location
If you wish to manually copy the public key,
Copy the complete text from
~/.ssh/id_rsa.pub. Executing the command
cat ~/.ssh/id_rsa.pubwill display the complete text in your terminal.
Login to your server and navigate to the location
If a directory
.sshdoesn't exist, create the directory by using the command
mkdir -p ~/.ssh
Create a file
~/.ssh/authorized_keysin the server
and copy the public key to it.
Disable password authentication
Since we are using ssh key based authentication from now on, we can disable password authentication in the server.
Open the file
/etc/ssh/sshd_configand locate the parameter
PasswordAuthenticationto no to disable password authentication.
Restart ssh daemon by executing the below command.
service sshd restart
You can forget your password now