Set up your first SSH keys

Use SSH keys for authentication without password when you are connecting to your server. simple and secure login process.

To Generate a new SSH Key

[root@server ~]$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/
The key fingerprint is:
SHA256:kxPyLTxxqwobFXoOxxxABaDD0xxnZzCB6xxxf38 root@server
The key's randomart image is:
+---[RSA 2048]----+
|=+==*            |
|xo.o =           |
|+oo.O .          |
|=o.* * o         |
|.x. = X S        |
| .   O *         |
|    o = o        |
|     + qo.x.   P |
|    . .xx+o..o.  |

First way: Copy the public key to your server using the command

[root@server ~]$ ssh-copy-id root@<instance_ip>
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/"
The authenticity of host '<instance_ip> (<instance_ip>)' can't be established.
ECDSA key fingerprint is SHA256:aF/iyxxxKqx1LUyM/uyr/xxxxxxxxxxx.
ECDSA key fingerprint is MD5:xx:c3:xx:48:b4:ef:xx:e4:58:a4:xx:14:c1:xx:c5:af.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@<instance_ip>'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@<instance_ip>'"
and check to make sure that only the key(s) you wanted were added.

Second way: Download the public key to your server using the Github, Gitlab

  • upload your key to Github or Gitlab: settings -> SSH keys -> New SSH key
  • after uoload the SSH key you can access key on Github, Gitlab

now you can import the SSH key using curl command

[root@server ~]$ curl -L >> ~/.ssh/authorized_keys
[root@server ~]$ curl -L >> ~/.ssh/authorized_keys
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1315  100  1315    0     0   6015      0 --:--:-- --:--:-- --:--:--  6032

note this way will import all keys on your github account

now you can access your server without password try:

ssh root@<instance_ip>

Turn off password authentication

With SSH key authentication, you can disable password authentication for SSH to prevent brute-forcing. open SSH configuration file

vim /etc/ssh/sshd_config

search for PasswordAuthentication and PermitRootLogin change it to:

PasswordAuthentication no
PermitRootLogin without-password

Restart the SSH service

systemctl restart sshd


Remember to always keep your private keys safe.