The ssh-keygen is used to generate ssh keys and is mostly used for authenticating to gitlab, github, bitbucket at work.
However we can use ssh keys to remote into a server without using passwords.
Generate a new pair of ssh keys
ssh-keygen is used to generate a new pair of keys In the below command
-bis the bit length. Most application we use 2048 or 4096-fspecifies the file to store the generated key in
ssh-keygen -b 4096 -f ~/.ssh/remoteserver
Entering a passphrase is optional and can be entered for additional security.
We will see two files generated in ~/.ssh folder. The file ending with .pub is the public key and can be shared.
remoteserver
remoteserver.pub
Transfer the public key to server
To transfer we use ssh-copy-id command In the below command
-ispecifies the path to the identity file (pubic key)- replace
userandhostnamewith the remote server details
ssh-copy-id -i ~/.ssh/remoteserver.pub user@hostname
- Accept any fingerprint by entering
yes - Enter the creds for the username when prompted
This will copy the public key to ~/.ssh folder inside authorized_keys file
Now run the below command. This will enable logging into server without entering password and providing the identity file (i.e. private key path)
ssh -i ~/.ssh/remoteserver user@hostname
Further reading: Refer my prior blog post managing-multiple-ssh-keys where we can create a
configfile and we don’t need to provide the path to the private key for each ssh session.
Disable password login
If you want to disable password logins and only connect using ssh keys then do the following.
- ssh into server
ssh user@hostname
- Goto the below path
cd /etc/ssh
- edit the file
sshd_config
nano sshd_config
- Set
PasswordAuthenticationtonoand restart ssh service
sudo service ssh restart
Now you will only be able to login with ssh keys