Set Up SSH Key-Based (Passwordless) Login on Linux Server
Typically, SSH keys is more secure and convenient than traditional password authentication. In this article, I’m going to show how to setup SSH key-based login on any linux server such as CentOS, Ubuntu. Let’s get started:
Table of Contents
Generate SSH Key
We want to login to our server from our PC without entering password. Let’s do it. From your PC, run this commad:
ssh-keygen -t rsa -b 4096 -C "[email protected]"
It will ask you to provide a file name.
Enter file in which to save the key (/home/username/.ssh/id_rsa):
We want to store in default file. Just hit ENTER button.
Then it’ll ask you to provide a passphrase. You can skip it. Just press ENTER button.
Enter passphrase (empty for no passphrase):
To verify your new SSH key pair is generated, run this command:
ls ~/.ssh/id_*
Output will look like:
/home/username/.ssh/id_rsa /home/username/.ssh/id_rsa.pub
We’ve successfully generated SSH key in our PC.
Copy Public Key to Server
We need to add our newly generated key to our server. We can copy with ssh-copy-id
utility. Run this command to copy:
ssh-copy-id remote_username@server_ip_address
If ssh-copy-id
is not available on your computer, you can copy SSH key to server using this command:
cat ~/.ssh/id_rsa.pub | ssh remote_username@server_ip_address "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
Then we need to enter the remote user password to login to server.
remote_username@server_ip_address's password:
After authenticating, the local file (~/.ssh/id_rsa.pub
) will be copied to the remote user’s ~/.ssh/authorized_keys
file.
Output:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'username@server_ip_address'"
and check to make sure that only the key(s) you wanted were added.
Login Using Key
Now just run this command to login to server:
ssh remote_username@server_ip_address
That’s all. Thanks for reading.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.